Skip to content

Instantly share code, notes, and snippets.

@raggi
Created May 14, 2012 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raggi/2698015 to your computer and use it in GitHub Desktop.
Save raggi/2698015 to your computer and use it in GitHub Desktop.
Thread safe counter
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