【问题标题】:How to count threads waiting for mutex?如何计算等待互斥锁的线程?
【发布时间】:2015-12-03 14:25:28
【问题描述】:

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

例如:

m= Mutex.new

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

m.nb_waiting_threads # => 1

【问题讨论】:

  • 据我所见。你为什么需要这个?不要爱上XY problem

标签: ruby concurrency mutex


【解决方案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.

【讨论】:

  • 谢谢!这是解决问题的好方法:)
猜你喜欢
  • 2017-07-10
  • 2012-06-13
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 2015-07-12
  • 1970-01-01
相关资源
最近更新 更多