rubymultithreadinglocal-variables

When do you need to pass arguments to `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

The document gives the example:

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

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]

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


Solution

  • 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