On 30 December 2012 22:43, Matthew Kerwin <matthew / kerwin.net.au> wrote:

> On 30 December 2012 21:21, Robert Klemme <shortcutter / googlemail.com>wrote:
>
>> On Sun, Dec 30, 2012 at 2:38 AM, Grant Schoep <lists / ruby-forum.com>
>> wrote:
>> > So, What is the reason for doing Example 1 versus Example 2. The 2nd
>> > example seems simpler in my book.  My guess is it has something to do
>> > with how the objects may be used outside the thread?
>>
>> See 7stud's examples.  It's not about objects but about scope of
>> variables.
>>
>> Here's another way to demonstrate the effect:
>>
>> $ ruby -e 'for i in 0..4; Thread.new(i) {|n| sleep 1;p [i,n]} end;sleep 2'
>> [4, 3]
>> [4, 4]
>> [4, 2]
>> [4, 1]
>> [4, 0]
>>
>> Kind regards
>>
>> robert
>>
>
> So does that mean these are functionally identical?
>
>     Thread.new(a) { |b| do_something_with b }
>
> .. and ..
>
>     Thread.new { b=a; do_something_with b }
>
> Or is there a potential race condition caused by possibly deferred
> execution of the block, which is avoided by performing the "renaming"
> assignment in the parent thread?  I'm trying to think of an example, but am
> having trouble.
>

Thought of one (sorry for replying to myself):

    a = 1
    loop do
      Thread.new { b=a; p b }
      a += 1
    end

.. where `a += 1` is likely to run before `b=a`; as opposed to ..

    a = 1
    loop do
      Thread.new(a) { |b| p b }
      a += 1
    end

.. where passing the value of _a_ to Thread#new is guaranteed to happen
before `a += 1`, so _b_ will always have the right value.

-- 
  Matthew Kerwin, B.Sc (CompSci) (Hons)
  http://matthew.kerwin.net.au/
  ABN: 59-013-727-651

  "You'll never find a programming language that frees
  you from the burden of clarifying your ideas." - xkcd