Ruby线程使用不同的参数调用相同的函数
发布时间:2020-12-17 02:25:11 所属栏目:百科 来源:网络整理
导读:我使用多个线程(例如10个线程)调用相同的 Ruby函数.每个线程将不同的参数传递给函数. 例: def test thread_no puts "In thread no." + thread_no.to_sendnum_threads = 6threads=[]for thread_no in 1..num_threads puts "Creating thread no. "+thread_no.
我使用多个线程(例如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,5,6)我能以某种方式实现这一点吗? 解决方法
问题是for循环.在Ruby中,它重用了一个变量.
所以线程主体的所有块都访问同一个变量.循环结束时,此变量为6.线程本身可能仅在循环结束后才开始. 您可以使用each-loops解决此问题.它们更干净地实现,每个循环变量本身都存在. (1..num_threads).each do | thread_no | puts "Creating thread no. "+thread_no.to_s threads << Thread.new{test(thread_no)} end 不幸的是,ruby中的循环是惊喜的来源.所以最好总是使用每个循环. 加成: threads << Thread.new(thread_no){|n| test(n) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |