如何将Monitor对象传递给Ruby中的两个线程对象?

创建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语句。 怎么做? 请给我示例代码。

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

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

 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