我遇到了同步线程的问题,我不知道怎么做,有人能帮帮我吗?
所以,问题是我必须以某种特定的顺序启动线程。 订单如下:
线程1和7可以同时进行,并且在其中一个完成之后,下一个线程被启动(即线程2或/和线程6),线程3和5的方式相同。 最后一个,在线程3和5完成运行之后,进入最后一个,线程4。
这是我开始使用的代码,但我在某种程度上陷入了队列实现。
MUTEX = Mutex.new
high_condition = ConditionVariable.new
low_condition = ConditionVariable.new
threads = []
7.times do |i|
threads << Thread.new{
MUTEX.synchronize {
Thread.current["number"] = i
you_shall_not_pass
}
}
end
threads.map(&:join)
def you_shall_not_pass
order = Thread.current["number"]
end
答案 0 :(得分:1)
使用Ruby的Queue
作为counting semaphore。它具有阻塞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