Does it have a crystal-lang Queue?

流过昼夜 提交于 2019-12-24 03:32:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!