如何计算等待互斥量的线程数?

How to count threads waiting for mutex?

是否有内置方法来计算等待互斥锁的线程数?

例如:

m= Mutex.new

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

m.nb_waiting_threads # => 1

没有内置方法来计算等待 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.