Created
May 2, 2020 23:54
-
-
Save lbarasti/4d36cb8608dc700a3f4a6273ae0d40c4 to your computer and use it in GitHub Desktop.
select use case 1: graceful termination
This file contains hidden or 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