Multithreads, years before and now

Hi guys, how are you?
Being taking a look at the threads behaviour in Ruby, I did that before
like year and a half later and now I found an old exercise-example that
I made before, so I’ve tried to reproduce it again, but I’ve found a
surprise for me. I was pretty sure about the results of this exercise,
because I remember that I did it, with irb, and from scripts and same
happens before. So I expected this now:

$v = 0

a = {1000000.times {$v += 1}}
b = {1000000.times {$v += 1}}
c = {1000000.times {$v += 1}}
d = {1000000.times {$v += 1}}

[a, b, c, d].each {|t| t.join}

puts $v
#=> 3172844

So this was an example from a book(I didn’t inveted it), to show the
use of #Mutex objects. What says in the book is that all the threads are
trying to access the same object and sometimes one pick an old value,
and that’s why you never reach 4000000. Then this follows:

semaphore =

a = {
1000000.times {
semaphore.synchronize {
$v += 1

#and with the others threads…

[a, b, c, d].each {|t| t.join}

puts $v
#=> 4000000

Now when I try to reproduce this now, whitout using the Mutex object, I
find that the result is 4000000, and I tested is hundred of times. Meaby
this is a trivial question, but I don’t know why this behaviour has
I have to say that before I was running Ruby 1.9.3 on Windows XP 32
bits and now(year and a half later) I’m running Windows 7 64 bits, still
running Ruby 1.9.3.
Well if you have some point of view or want to test this snippets just
go, and let me know :). Thanks.

On Mar 30, 2013, at 5:20 PM, “Damin M. Gonzlez” [email protected]

From my understanding the GIL/GVL [1] in MRI[2] causes the initial
example to behave nearly the same as the example using a Mutex (only a
single thread running ruby code executes at a time). If you were to try
the example above in an alternate ruby implementation without the
GIL/GVL you would likely get results similar to what you were looking

I recently read a couple of good articles[3][ and [4] that explains this
pretty well.

Robert Jackson

[1] - Global interpreter lock - Wikipedia
[2] - Ruby MRI - Wikipedia
[3] -
[4] -

Thanks for answer Robert.