Skip to content

Instantly share code, notes, and snippets.

@spastorino
Created November 1, 2011 02:00
Show Gist options
  • Save spastorino/1329640 to your computer and use it in GitHub Desktop.
Save spastorino/1329640 to your computer and use it in GitHub Desktop.
require 'thread'
mutex = Mutex.new
i = 0
t1 = Thread.new do
1_000_000.times do
mutex.synchronize do
i += 1
end
end
end
t2 = Thread.new do
1_000_000.times do
mutex.synchronize do
i += 1
end
end
end
t1.join
t2.join
puts i
#####################
➜ /tmp ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.2.0]
➜ /tmp time ruby count.rb
2000000
ruby count.rb 0.72s user 0.03s system 97% cpu 0.771 total
➜ /tmp ruby -v
jruby 1.6.5 (ruby-1.8.7-p330) (2011-10-25 9dcd388) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_26) [darwin-x86_64-java]
➜ /tmp time ruby count.rb
2000000
ruby count.rb 2.72s user 1.24s system 146% cpu 2.694 total
➜ /tmp ruby -v
rubinius 2.0.0dev (1.8.7 acf6926c yyyy-mm-dd JI) [x86_64-apple-darwin11.2.0]
➜ /tmp time ruby count.rb
2000000
ruby count.rb 6.62s user 8.95s system 109% cpu 14.179 total
@headius
Copy link

headius commented Nov 1, 2011

Oh, last note on this.

Keep in mind that on all the implementations, you're talking about overhead in the µsec range for locking the mutex. I doubt you'll see that matter in any real-world app, especially when the block contains something more substantial than incrementing a Fixnum :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment