Created
May 14, 2012 23:12
-
-
Save raggi/2698015 to your computer and use it in GitHub Desktop.
Thread safe counter
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
class ThreadsafeCounter | |
include Comparable | |
def initialize(initial = 0) | |
@mutex = Mutex.new | |
@count = initial + 0 | |
end | |
def incr | |
@mutex.synchronize { @count += 1 } | |
self | |
end | |
def decr | |
@mutex.synchronize { @count -= 1 } | |
self | |
end | |
def value | |
# N.B. The + 0 here is because you cannot #dup BigNums, but they are real | |
# objects. Real objects can be subject to race conditions otherwise avoided | |
# with immediates. This appears to be the most portable API to use to ensure | |
# you get a "safe" object back. | |
@mutex.synchronize { @count + 0 } | |
end | |
alias to_i value | |
def <=>(other) | |
to_i <=> other.to_i | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment