如何将 Monitor 对象传递给 Ruby 中的两个线程对象? [英] How to pass an Monitor object to two thread objects in Ruby?

查看:37
本文介绍了如何将 Monitor 对象传递给 Ruby 中的两个线程对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When create a Ruby thread, you give a block after Thread.new, and after new, the thread starts execution immediately. And Ruby use Monitor class as mutex lock. But I don't understand how to pass a monitor object to thread execution body. See the following sample code:

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> 声明.怎么做?请给我示例代码.

I want to new a Monitor object, and pass it to both thread1 and thread2 to synchronize the puts statement. How to do it? Please give me sample code.

这个问题可以问得更笼统.如何将对象传递给线程执行块?

This question could be asked more generally. How to pass an object to thread execution block?

推荐答案

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

Thread is no different than any other classes. You can use any valid variable.

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

这篇关于如何将 Monitor 对象传递给 Ruby 中的两个线程对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆