2012-07-25 4 views

답변

1

:

큐에서 데이터를 검색. 큐가 비어 있으면 호출 스레드는 데이터가 큐에 푸시 될 때까지 일시 중단됩니다. 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 

이제 두 개의 스레드를보십시오. 소비자 스레드는 큐가 비어있을 때 일시 중단되지만 두 번째 스레드가 큐에 무엇인가를 푸시하면 다시 활성화됩니다.