Skip to content

Instantly share code, notes, and snippets.

@Dakad
Forked from lbarasti/select_send_receive.cr
Created January 11, 2022 14:46
Show Gist options
  • Save Dakad/494ecd4c2f84257819adf4f55d250a94 to your computer and use it in GitHub Desktop.
Save Dakad/494ecd4c2f84257819adf4f55d250a94 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