Skip to content

Instantly share code, notes, and snippets.

@lbarasti
Created May 2, 2020 23:50
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/c73927c04002f3b5c475197be01de113 to your computer and use it in GitHub Desktop.
Save lbarasti/c73927c04002f3b5c475197be01de113 to your computer and use it in GitHub Desktop.
use case 2: mixing send and receive
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 / 2; rand }
result = Channel(Float64).new
spawn(name: "sum calculator") do
sum = 0.0
loop do
select
when v = values.receive
log "adding #{v}"
sum += v
when result.send sum
end
end
end
3.times {
sleep rand
sum = result.receive
log "#{sum}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment