1

我在同步线程时遇到问题,我不知道该怎么做,有人可以帮助我吗?

所以,问题是我必须以某种特定的顺序启动线程。顺序如下:

线程 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
4

1 回答 1

1

使用 RubyQueue作为计数信号量。它具有阻塞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
于 2015-12-04T16:18:19.827 回答