没有内置的方法来计算等待a的线程Mutex
,但是如果你可以将你的问题转换为使用a Queue
,那么就有一种num_waiting
方法.
要Mutex
使用a 模拟a 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.