【发布时间】:2015-11-10 08:22:14
【问题描述】:
我正在使用多个线程(例如 10 个线程)调用相同的 Ruby 函数。每个线程将不同的参数传递给函数。
例子:
def test thread_no
puts "In thread no." + thread_no.to_s
end
num_threads = 6
threads=[]
for thread_no in 1..num_threads
puts "Creating thread no. "+thread_no.to_s
threads << Thread.new{test(thread_no)}
end
threads.each { |thr| thr.join }
输出:
创建线程号1
创建线程号2
创建线程号3
创建线程号4
在线程号 4
创建线程号5
创建线程号6
在线程号 6
在线程号 6
在线程号 6
在线程号 6
在线程号 6
当然我想得到输出:在线程号中。 1 (2,3,4,5,6) 我能以某种方式实现这一点吗?
【问题讨论】:
-
不知道 ruby,但应该应用与往常相同的解决方案:将局部变量 local_thread_no 用于 thread_no 传递给线程构造函数时
标签: ruby multithreading