我正在学习Fibers\coroutines的概念以及在Crystal中的实现,但是遇到了一些困难。
希望这里是一个合适的地方来寻求帮助,如果不是,我完全接受"不在这里"的答案 :)
这是我在Ruby中处理多线程的常规方式:
threads = []
max_threads = 10
loop do
begin
threads << Thread.new do
helper_method(1,2,3,4)
end
rescue Exception => e
puts "Error Starting thread"
end
begin
threads = threads.select { |t| t.alive? ? true : (t.join; false) }
while threads.size >= max_threads
puts 'Got Maximum threads'
sleep 1
threads = threads.select { |t| t.alive? ? true : (t.join; false) }
end
rescue Exception => e
puts e
end
end
我通常会这样打开一个新的线程,通常是针对传入连接或其他一些事情,将该线程添加到线程数组中,然后检查我是否有比我想要的更多的线程。
在Crystal中使用spawn/channels/fibers等方式实现类似功能的好方法是什么?