Skip to content

Instantly share code, notes, and snippets.

@avdi
Created September 26, 2013 18:54
Show Gist options
  • Save avdi/6718863 to your computer and use it in GitHub Desktop.
Save avdi/6718863 to your computer and use it in GitHub Desktop.
require "thread"
Thread.abort_on_exception = true
def none
counter = 0
threads = 10.times.map do
Thread.new do
100.times do
counter += 1
end
end
end
threads.each(&:join)
counter
end
def mutex
counter = 0
lock = Mutex.new
threads = 10.times.map do
Thread.new do
100.times do
lock.synchronize { counter += 1 }
end
end
end
threads.each(&:join)
counter
end
def atomic
require "atomic"
counter = Atomic.new(0)
threads = 10.times.map do
Thread.new do
100.times do
counter.update{|v| v + 1}
end
end
end
threads.each(&:join)
counter.value
end
require "benchmark"
n = 10
Benchmark.bm(7) do |b|
b.report("none") { n.times { none } }
b.report("mutex") { n.times {mutex } }
b.report("atomic") { n.times { atomic } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment