问题描述
如何实现模式生产者-水晶郎上的消费者?我正在寻找类似的内容- http://ruby-doc.org /core-2.2.0/Queue.html 可能我需要使用Channel
,但我不知道如何使用..,因为它正在等待消费者"的接收.
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.htmlProbably i need to use Channel
, but I don't understand how.. because it's wait while "consumer" will receive.
我的意思是:
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
推荐答案
您是对的,使用渠道是解决Crystal中的并发通信的好方法.请注意,默认情况下,通道在接收到一个值之前只能存储一个值.
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.
但是您可以使用缓冲的Channel来将多个值发送到Channel,而不必立即接收它们.本质上,这是一个FIFO队列,在该队列中,一端添加新项,另一端删除新项.
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)
这篇关于它是否具有水晶语言队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!