【发布时间】:2021-11-29 23:09:23
【问题描述】:
前几天我遇到了一个问题,我花了 2 个小时在错误的地方寻找答案。
在此过程中,我将代码精简为以下版本。只要我在创建线程的循环中有sleep(0.1),这里的线程就可以工作。
如果省略该行,则创建所有线程 - 但只有线程 7 会实际使用队列中的数据。
有了这个“hack”,我确实有一个可行的解决方案,但我并不满意。我真的很好奇为什么会这样。
我在 Windows 2.4.1p111 下使用的是相当旧的 ruby 版本。但是,我能够通过新的 ruby 3.0.2p107 安装重现相同的行为
#!/usr/bin/env ruby
@q = Queue.new
# Get all projects (would be a list of directories)
projects = [*0..100]
projects.each do |project|
@q.push project
end
def worker(num)
while not @q.empty?
puts "Thread: #{num} Project: #{@q.pop}"
sleep(0.5)
end
end
threads=[]
for i in 1..7 do
threads << Thread.new { worker(i) }
sleep(0.1) # Threading does not work without this line - but why?
end
threads.each {|thread| puts thread.join }
puts "done"
【问题讨论】:
标签: ruby multithreading queue sleep worker