加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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
?在第4号线中
?创建线程号.五
?创建线程号. 6
?在第6号线中
?在第6号线中
?在第6号线中
?在第6号线中
?在第6号线中

当然我想得到输出:在线程号. 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中的循环是惊喜的来源.所以最好总是使用每个循环.

加成:
你还给Thread.new一个或几个参数,并将这些参数传递给线程体块.这样,您可以确保块在其自身范围之外不使用vars,因此它也适用于for循环.

threads <<  Thread.new(thread_no){|n| test(n) }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读