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

时间:2015-12-03 14:25:29

标签: ruby concurrency mutex

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

例如:

m= Mutex.new

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

m.nb_waiting_threads # => 1

1 个答案:

答案 0 :(得分:6)

没有内置方式来计算等待Mutex的线程,但是如果您可以将问题转换为使用Queue,则会出现{{3}方法。

要使用Mutex模拟Queue,您将获得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.