Tho*_*tre 4 ruby concurrency mutex
是否有内置的方法来计算等待互斥锁的线程数?
例如:
m= Mutex.new
2.times do
Thread.new do
m.lock
end
end
m.nb_waiting_threads # => 1
Run Code Online (Sandbox Code Playgroud)
没有内置的方法来计算等待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)
Run Code Online (Sandbox Code Playgroud)
$ 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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |