Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Created January 14, 2013 05:26
Show Gist options
  • Save thejefflarson/4527928 to your computer and use it in GitHub Desktop.
Save thejefflarson/4527928 to your computer and use it in GitHub Desktop.
require 'fcntl'
require 'thread'
class ConcurrentFile
def initialize
@out = File.open 't', 'w'
@mutex = Mutex.new
end
def lock
@out.flock(File::LOCK_EX)
@mutex.synchronize do
@data = File.read('t').to_i || 0
@out.pos = 0
@out.write @data + 1
@out.flush
end
ensure
@out.flock(File::LOCK_UN)
end
end
a = ConcurrentFile.new
b = ConcurrentFile.new
c = Thread.new {
1000.times { a.lock }
}
d = Thread.new {
1000.times { b.lock }
}
c.join
d.join
p File.read('t')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment