Skip to content

Instantly share code, notes, and snippets.

@youpy
Created February 8, 2010 20:05
Show Gist options
  • Select an option

  • Save youpy/298525 to your computer and use it in GitHub Desktop.

Select an option

Save youpy/298525 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'spec'
require 'benchmark'
describe 'File#flock' do
before do
@lock_file = '/tmp/xxx.lock'
end
after do
File.unlink(@lock_file)
end
it 'should fail with same instance of File' do
f = File.open(@lock_file, 'w')
try_lock(f, f).should_not be_true
end
it 'should success with different instances of File' do
f1 = File.open(@lock_file, 'w')
f2 = File.open(@lock_file, 'w')
try_lock(f1, f2).should be_true
end
def try_lock(f1, f2)
threads = []
Benchmark.measure do
threads << Thread.new do
sleep 1
f1.flock(File::LOCK_EX)
sleep 2
f1.flock(File::LOCK_UN)
end
threads << Thread.new do
f2.flock(File::LOCK_EX)
sleep 2
f2.flock(File::LOCK_UN)
end
threads.each do |thread|
thread.join
end
end.real.to_i == 4
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment