7stud -- <lists / ruby-forum.com> wrote:

> Matthew Kerwin wrote in post #1090641:
> >
> > 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`;
>
> What makes you think that?


Experience in multithreaded environments. Without an explicit mutex or
other locking mechanism (or call to Thread#join) there's no guarantee that
either will run before the other.  I know that in MRI the GVL is a large
player, but I'm not being implementation-specific here.

If I really had to guess, in a truly parallel multithreaded environment,
assuming that the block begins execution at the same instant as the line
after Thread.new, I'd guess that the `b=a` operation would happen before
the `a = ...`, assuming that `a += 1` is actually broken down into `a = a +
1` which has an extra operation and so should take longer. However in a
less parallel system I would have assumed the current thread would execute
a bit before the child thread was given some CPU time, so `a += 1` would
have a chance to complete before `b=a`. In either case it's something over
which I as the programmer do not have any control.

Matma Rex <matma.rex / gmail.com> wrote:
> There's another thing apart from the race conditions. These are mostly
equivalent (except for what you've already said) only if there is no
variable called `b` in the outer scope - if there was one, in your second
example `b=a` will assign to it and change the value outside the thread. In
the first case, the "outer" `b` will simple be inaccessible inside the
thread, but its value outside the thread won't be changed.

Ah, that's a really good point. I'd forgotten that 1.9 masks variables with
the same name as block parameters. Now that you've said it, I remember
having to refactor a bunch of OptParse code that used to use:

    on('-x', Integer, 'foobar') {|$x| }

-- 
  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