2015-12-03 59 views
3

有一種內置的方法來計算等待互斥量的線程數量嗎?如何計算等待互斥量的線程?

例如:

m= Mutex.new 

2.times do 
    Thread.new do 
    m.lock 
    end 
end 

m.nb_waiting_threads # => 1 
+1

不受限制,只要我能看到。你爲什麼需要這個?不要因爲[XY問題](http://xyproblem.info/)。 – Thomas

回答

6

有沒有內置的方法來計算線程都在等待一個Mutex,但如果你可以轉換使用Queue您的問題,有一個num_waiting方法。

要使用Queue模擬Mutex,您需要獲得pop的鎖定並釋放鎖定push的值。您的不變之處在於隊列在任何給定時刻只包含0或1個項目。

require 'thread' 

semaphore = Queue.new 
semaphore.push(1) # Make synchronization token available 

threads = [] 
5.times do |i| 
    threads << Thread.new do 
    semaphore.pop # Blocks until token available 
    puts "Thread #{i} working, #{semaphore.num_waiting} threads waiting." 
    sleep rand(3) # Do work 
    semaphore.push(1) # Release token 
    end 
end 

threads.each(&:join) 
$ ruby queue_lock.rb 
Thread 0 working, 0 threads waiting. 
Thread 1 working, 3 threads waiting. 
Thread 3 working, 2 threads waiting. 
Thread 2 working, 1 threads waiting. 
Thread 4 working, 0 threads waiting. 
+0

謝謝!這是一個很好的解決問題的方法:) – ThomasSevestre