2012-07-25 49 views

回答

1

Ruby documentation for Queue#pop

從隊列中檢索數據。如果隊列爲空,則將調用線程掛起,直到將數據推入隊列。如果non_block爲true,則該線程不會掛起,並引發異常。

您正在使用單線程,因此您的隊列永遠不會包含任何對象,因此您的線程會永久掛起(死鎖)。

試試這個

require "thread" 

queue = Queue.new 
thread1 = Thread.new do 
    5.times do |i| 
    x = queue.pop 
    sleep rand(i) # simulate workload 
    puts "taken #{x} from queue!" 
    end 
end 

thread2 = Thread.new do 
    5.times do |i| 
    sleep rand(i) # simulate workload 
    queue.push i 
    puts "pushed #{i} to the queue!" 
    end 
end 

thread1.join 

你有兩個線程,因此您將不會遇到死鎖。當隊列爲空時,消費者線程將被掛起,但當第二個線程將某些東西推送到隊列時,它將再次變爲活動狀態。