Created
January 6, 2012 21:44
-
-
Save mpage/1572534 to your computer and use it in GitHub Desktop.
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 '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