Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lbarasti
Created May 2, 2020 23:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lbarasti/4d36cb8608dc700a3f4a6273ae0d40c4 to your computer and use it in GitHub Desktop.
Save lbarasti/4d36cb8608dc700a3f4a6273ae0d40c4 to your computer and use it in GitHub Desktop.
select use case 1: graceful termination
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