From: Matthew Kerwin Date: 2012-12-30T21:43:53+09:00 Subject: Re: Thread.start(variables) do question --f46d042f95be2ed22804d210d71f Content-Type: text/plain; charset=ISO-8859-1 On 30 December 2012 21:21, Robert Klemme wrote: > On Sun, Dec 30, 2012 at 2:38 AM, Grant Schoep > 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. -- 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 --f46d042f95be2ed22804d210d71f Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
On 30 December 2012 21:21, Robert Klemme <shortc= utter@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. =A0My guess is it has something to d= o
> with how the objects may be used outside the thread?

See 7stud's examples. =A0It's not about objects but about sco= pe 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
=A0
So does that mean = these are functionally identical?

=A0 =A0 Thread.new(a) { |b| do_something_with b= }

.. and ..

=A0 =A0 Thread.new { b=3Da; 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 "r= enaming" assignment in the parent thread? =A0I'm trying to think o= f an example, but am having trouble.

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

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