1
我想创建多个线程并返回数据结构的结果,我读了Queue
是线程安全的,但是当我运行代码时,它不会产生预期的结果。不是ruby队列线程安全为什么队列不同步?
require 'thread'
class ThreadsTest
queue = Queue.new
threads = []
for i in 1..10
threads << Thread.new do
queue << i
end
end
threads.each { |t| t.join }
for i in 1..10
puts queue.pop()
end
end
代码打印:(总是有少许差别)
4
4
4
4
10
10
10
10
10
10
我是通过10.
期望数字1我试图synchronize
它手动无济于事:
mutex = Mutex.new
for i in 1..10
threads << Thread.new do
mutex.synchronize do
queue << i
end
end
end
我错过了什么?
顺便说一句,这是奇怪的把这样的代码对入'class'块。你应该用一种方法来包装它。 – Stefan