Is there a builtin way to count the number of threads waiting for a mutex?
For instance:
m= Mutex.new
2.times do
Thread.new do
m.lock
end
end
m.nb_waiting_threads # => 1
There's no built-in way to count threads waiting on a Mutex
, but if you can convert your problem to use a Queue
, there's a num_waiting
method.
To simulate a Mutex
with a Queue
, you would acquire the lock with pop
and release the lock by push
ing a value. Your invariant is that the queue only contains 0 or 1 items at any given moment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With