问题
How to realize pattern producer - consumer on crystal lang? I'am looking for something like that - http://ruby-doc.org/core-2.2.0/Queue.html
Probably i need to use Channel, but I don't understand how.. because it's wait while "consumer" will receive.
I mean:
channel = Channel(Int32).new
spawn do
15.times do |i|
# ... do something that take a time
puts "send #{i}"
channel.send i # paused while someone receive, but i want to continue do the job that takes a time..
end
end
spawn do
loop do
i = channel.receive
puts "receive #{i}"
sleep 0.5
end
end
sleep 7.5
回答1:
You're right, using a Channel is a great way to solve conncurent communication in Crystal. Note that by default a Channel can only store one value until it is received.
But you can use a buffered Channel to be able to send multiple values to the Channel and they don't need to be received immediately. This is essentially a FIFO queue where new items are added at one end and removed from the other.
# Create a channel with a buffer for 32 values
channel = Channel(Int32).new(32)
来源:https://stackoverflow.com/questions/48128133/does-it-have-a-crystal-lang-queue