Created
February 8, 2010 20:05
-
-
Save youpy/298525 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 '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