Bug #2337: "for object in collection" syntax not thread-safe
http://redmine.ruby-lang.org/issues/show/2337

Author: John-Michael fischer
Status: Open, Priority: High
ruby -v: ruby 1.9.1p243 (2009-07-16 revision 24175) [x86_64-linux]

After spending many hours shooting in the dark I have discovered the following.

METHOD 1
The following code _will not_ execute as one would expect.
for object in collection
  Thread.new(object) do
    some_method(object)
  end
end

METHOD 2
The following code _will_ execute as one would expect as long as [important] obj_scope has not been used outside of the loop before.
If obj_scope has been used outside the loop previous to this code, then its execution will be identical to the behavior above.
collection.size.times do |i|
  obj_scope = collection[i]
  Thread.new(obj_scope) do
    some_method(obj_scope)
  end
end

The expected behavior is that some_method will one run once for each object in collection in its own thread.
When using METHOD 1 what actually happens is some_method is called precisely collection.size times, but the object passed can be the same object 3 or 4 times.  The end result is that several objects in collection will be used many times for the function call and some objects will never be used.

I've attached sample code which illustrates my issue.  Please change the first line from "#!/usr/um/bin/ruby" to the location of _your_ ruby 1.9.1 interpreter.


----------------------------------------
http://redmine.ruby-lang.org