From: "Damián M. González" Date: 2013-03-31T06:20:32+09:00 Subject: 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 = Thread.new {1000000.times {$v += 1}} b = Thread.new {1000000.times {$v += 1}} c = Thread.new {1000000.times {$v += 1}} d = Thread.new {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 = Mutex.new a = Thread.new { 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 changed. 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. -- Posted via http://www.ruby-forum.com/.