Skip to content

Instantly share code, notes, and snippets.

@mpage
Created January 6, 2012 21:44
Show Gist options
  • Save mpage/1572534 to your computer and use it in GitHub Desktop.
Save mpage/1572534 to your computer and use it in GitHub Desktop.
require 'tempfile'
require 'thread'
$stdout_mutex = Mutex.new
def thread_log(msg)
$stdout_mutex.synchronize do
puts "#{Time.now} #{Thread.current} -- #{msg}"
STDOUT.flush
end
end
def do_flock(lockfile)
File.open(lockfile, 'w+') do |f|
thread_log("Acquiring lock")
f.flock(File::LOCK_EX)
thread_log("Acquired lock")
thread_log("Sleeping 10")
sleep(10)
# Not strictly necessary as exiting the block closes the fd
# which releases the lock
f.flock(File::LOCK_UN)
end
end
lockfile = Tempfile.new("test_flock")
begin
t1 = Thread.new { do_flock(lockfile.path) }
t2 = Thread.new { do_flock(lockfile.path) }
t3 = Thread.new do
loop do
thread_log("Still active")
sleep(1)
end
end
t1.join
t2.join
ensure
lockfile.close
lockfile.unlink
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment