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それを両方に渡しthread1、ステートメントthread2を同期させたい。putsどうやってするの?サンプルコードを教えてください。

この質問は、より一般的に尋ねられる可能性があります。オブジェクトをスレッド実行ブロックに渡す方法は?

4

1 に答える 1

0

スレッドは他のクラスと同じです。任意の有効な変数を使用できます。

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 に答える