From: Josh Cheek Date: 2011-10-19T16:11:24+09:00 Subject: Re: Ruby and threading --20cf3002584ccb3dc604afa18b62 Content-Type: text/plain; charset=ISO-8859-1 On Sun, Oct 16, 2011 at 4:03 AM, Josh Cheek wrote: > On Sun, Oct 16, 2011 at 3:50 AM, Carter Cheng wrote: > >> Hello, >> >> Is the current ruby 1.9.2 multithreaded at the OS level? >> >> Regards, >> >> Carter. >> > > For MRI, yes, but it has a global interpreter lock. Here's a blog that > explains all the nuances. > http://www.engineyard.com/blog/2011/ruby-concurrency-and-you/ > A great followup to this post, explains why the GIL exists http://merbist.com/2011/10/18/data-safety-and-gil-removal/ When I ran the code Matt provides under MRI 1.9.3 (has GIL) and Rubinius, JRuby, MacRuby (native threads, no GIL): $ rvm 1.9.3-rc1,rbx-2.0.0pre,jruby-1.6.4,macruby-0.10 do ruby needs_gil.rb ruby-1.9.3-rc1 0.064 seconds 400000 elements in array (should be 400000) rbx-2.0.0pre 0.232 seconds 398877 elements in array (should be 400000) jruby-1.6.4 0.069 seconds 398709 elements in array (should be 400000) macruby-0.10 0.076 seconds 366231 elements in array (should be 400000) $ cat needs_gil.rb puts '', ENV['RUBY_VERSION'] @array, threads = [], [] start = Time.now 4.times do threads << Thread.new { (1..100_000).each {|n| @array << n} } end threads.each{|t| t.join } stop = Time.now puts "%0.3f seconds" % (stop - start), @array.size Note: * Other times I ran it under Rubinius, the array got corrupted or something "Tuple::copy_from: index 8092 out of bounds for size 5395 (Rubinius::ObjectBoundsExceededError)" * Other times I ran it under JRuby, it detected the corrupt data with 'ConcurrencyError: Detected invalid array contents due to unsynchronized modifications with concurrent users' * I ran this a whole bunch of times, sometimes MRI was fastest, sometimes MacRuby, sometimes JRuby (MRI was fastest most consistently, though) Thoughts: * MRI has a GIL, thus keeping the data safe, and still performs equivalently with other implementations (for this admittedly limited test), so do benchmarks to decide if this will be worthwhile. It's not a fluke that Matz wants to keep the GIL. * I'm glad JRuby notices the corrupt data (though not always) I'm a big fan of fail-fast * Has JRuby fixed their startup time issue? I ran this a lot of times and didn't notice any of the lag I used to. --20cf3002584ccb3dc604afa18b62--