Created
July 6, 2011 21:59
-
-
Save mikbe/1068453 to your computer and use it in GitHub Desktop.
Class level mutex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
module SuperMutex | |
attr_reader :bar | |
def self.included(base) | |
base.extend(ThreadSafeClassMethods) | |
base.threadsafe_class_mutex = Mutex.new | |
end | |
module ThreadSafeClassMethods | |
attr_accessor :threadsafe_class_mutex | |
end | |
def threadsafe_mutex | |
self.class.threadsafe_class_mutex.synchronize { | |
@mutex ||= Mutex.new | |
} | |
end | |
def some_method | |
threadsafe_mutex.synchronize { | |
@bar ||= 0 | |
@bar += 1 | |
} | |
end | |
end | |
class Foo | |
include SuperMutex | |
end | |
threads = [] | |
Thread.abort_on_exception | |
thread_count = 700 | |
Benchmark.bmbm(7) do |x| | |
x.report do | |
# it takes about half a second to create 1,000 threads so a full second is plenty to wait | |
start = Time.now + 1.0 | |
thread_count.times do | |
threads << Thread.new{sleep (start - Time.now); foo = Foo.new; 1000.times{foo.some_method} } | |
end | |
threads.each { |t| t.join } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment