使用 RubyQueue
作为计数信号量。它具有阻塞push
和pop
操作,可用于将有限数量的令牌分发给线程,要求每个线程在运行之前获取令牌并在完成时释放令牌。如果您使用 2 个令牌初始化队列,您可以确保一次只运行 2 个线程,并且您可以按照您喜欢的任何顺序创建线程。
require 'thread'
semaphore = Queue.new
2.times { semaphore.push(1) } # Add two concurrency tokens
puts "#{semaphore.size} available tokens"
threads = []
[1, 7, 2, 6, 3, 5, 4].each do |i|
puts "Enqueueing thread #{i}"
threads << Thread.new do
semaphore.pop # Acquire token
puts "#{Time.now} Thread #{i} running. #{semaphore.size} available tokens. #{semaphore.num_waiting} threads waiting."
sleep(rand(10)) # Simulate work
semaphore.push(1) # Release token
end
end
threads.each(&:join)
puts "#{semaphore.size} available tokens"
$ ruby counting_semaphore.rb
2 available tokens
Enqueueing thread 1
Enqueueing thread 7
2015-12-04 08:17:11 -0800 Thread 7 running. 1 available tokens. 0 threads waiting.
2015-12-04 08:17:11 -0800 Thread 1 running. 0 available tokens. 0 threads waiting.
Enqueueing thread 2
Enqueueing thread 6
2015-12-04 08:17:11 -0800 Thread 2 running. 0 available tokens. 0 threads waiting.
Enqueueing thread 3
Enqueueing thread 5
Enqueueing thread 4
2015-12-04 08:17:19 -0800 Thread 6 running. 0 available tokens. 3 threads waiting.
2015-12-04 08:17:19 -0800 Thread 5 running. 0 available tokens. 2 threads waiting.
2015-12-04 08:17:21 -0800 Thread 3 running. 0 available tokens. 1 threads waiting.
2015-12-04 08:17:22 -0800 Thread 4 running. 0 available tokens. 0 threads waiting.
2 available tokens