2013-10-25 139 views
1

我有一个同步线程的问题,我不知道该怎么做,有人可以帮助我吗?Ruby多线程队列

所以,事情是我必须以某种特定的顺序启动线程。 订单如下:

线程1和线程7可以同时运行,其中一个线程完成后,下一个线程启动(即线程2或/和线程6),线程3 (五) ,最后一个,两个线程后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

你能告诉我们更多关于预期的产出和你得到? – JunaidKirkire

+0

欢迎来到StackOverflow!感谢您发布您的代码,但请在您的问题中多加一点说明:您有什么问题,您期望得到什么结果,以及[您尝试过什么](http://whathaveyoutried.com)到目前为止?通过[问题清单](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)将帮助我们更好地回答你的问题。谢谢! –

+0

预期的输出可以是这样的: ' 线程1已经完成了它的任务 线程2已经完成了它的任务 Thread7已经完成了它的任务 Thread3已经完成了它的任务 Thread6已经完成了它的任务 Thread5已经完成了它的任务 Thread4有完成任务 ' 输出并不重要,问题是以适当的方式启动它们 –

回答

1

使用Ruby的Queue作为counting semaphore。它阻止了pushpop操作,您可以使用该操作将有限数量的标记分发给线程,要求每个线程在运行之前获取令牌并在完成时释放令牌。如果使用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