1

创建 Ruby 线程时,在 之后给一个块Thread.new,在 new 之后,线程立即开始执行。Ruby 使用Monitor类作为互斥锁。但我不明白如何将监视器对象传递给线程执行体。请参阅以下示例代码:

thread1 = Thread.new do
  sum=0
  1.upto(10) {|x| sum = sum + x}
  puts("The sum of the first 10 integers is #{sum}")
end
thread2 = Thread.new do
  product=1
  1.upto(10) {|x| product = product * x}
  puts("The product of the first 10 integers is #{product}")
end
thread1.join
thread2.join

我想新建一个Monitor对象,并将其传递给两者thread1thread2同步puts语句。怎么做?请给我示例代码。

这个问题可以问得更普遍。如何将对象传递给线程执行块?

4

1 回答 1

0

Thread与任何其他类没有什么不同。您可以使用任何有效的变量。

require 'monitor'

lock = Monitor.new

product=1
sum=0

thread1 = Thread.new do
  1.upto(10) {|x|
    sum = sum + x
    lock.synchronize do
      puts product
    end
  }
  puts("The sum of the first 10 integers is #{sum}")
end
thread2 = Thread.new do
  1.upto(10) {|x|
    product = product * x
    lock.synchronize do
      puts sum
    end
  }
  puts("The product of the first 10 integers is #{product}")
end
thread1.join
thread2.join
于 2013-08-26T06:34:40.277 回答