Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count threads waiting for mutex?

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
like image 436
Thomas Avatar asked Dec 03 '15 14:12

Thomas


1 Answers

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 pushing 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.
like image 122
Kristján Avatar answered Nov 15 '22 06:11

Kristján