-
-
Save Dakad/b4e0d04ba18febc3ea14b624e6ad2648 to your computer and use it in GitHub Desktop.
select use case 1: graceful termination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def producer(name : String, &generator : -> T) forall T | |
Channel(T).new.tap { |ch| | |
spawn(name: name) do | |
loop do | |
ch.send generator.call | |
end | |
end | |
} | |
end | |
def log(msg : String) | |
puts "#{Fiber.current.name}: #{msg}" | |
end | |
values = producer("rand") { sleep rand; rand } | |
terminate = Channel(Nil).new | |
done = Channel(Nil).new | |
spawn(name: "echo") do | |
loop do | |
select | |
when v = values.receive | |
log "#{v}" | |
when terminate.receive? | |
break | |
end | |
end | |
log "cleanup completed" | |
done.close | |
end | |
sleep 2 | |
# main fiber | |
terminate.close | |
done.receive? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment