您何时需要将参数传递给Thread.new? [英] When do you need to pass arguments to `Thread.new`?

查看:279
本文介绍了您何时需要将参数传递给Thread.new?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线程外部定义的局部变量似乎从内部可见,因此Thread.new的以下两种用法似乎是相同的:

Local variables defined outside of a thread seem to be visible from inside so that the following two uses of Thread.new seem to be the same:

a = :foo
Thread.new{puts a} # => :foo
Thread.new(a){|a| puts a} # => :foo

文档给出了示例:

arr = []
a, b, c = 1, 2, 3
Thread.new(a,b,c){|d, e, f| arr << d << e << f}.join
arr #=> [1, 2, 3]

但是由于从创建的线程内部可以看到abc,因此它也应与以下内容相同:

but since a, b, c are visible from inside of the created thread, this should also be the same as:

arr = []
a, b, c = 1, 2, 3
Thread.new{d, e, f = a, b, c; arr << d << e << f}.join
arr #=> [1, 2, 3]

有什么区别吗?您何时需要将局部变量作为参数传递给Thread.new?

Is there any difference? When do you need to pass local variables as arguments to Thread.new?

推荐答案

当您将变量传递给这样的线程时,该线程将对该变量进行本地复制并使用该变量,因此对其进行修改不会影响该变量.传入线程之外的变量

When you pass a variable into a thread like that, then the thread makes a local copy of the variable and uses it, so modifications to it do not affect the variable outside of the thread you passed in

a = "foo"
Thread.new{ a = "new"}
p a # => "new"
Thread.new(a){|d| d = "old"} 
p a # => "new"
p d # => undefined

这篇关于您何时需要将参数传递给Thread.new?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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