When do you need to pass arguments to `Thread.new`?

后端 未结 2 665
旧时难觅i
旧时难觅i 2021-02-12 20:25

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 = :fo         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-02-12 20:44

    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
    

提交回复
热议问题