LoginSignup
19
19

More than 5 years have passed since last update.

複数プロセス間での排他制御

Last updated at Posted at 2012-04-21

File.flock を使うのが簡単、という結論に到達した。

require 'timeout'
class AccessDenied < StandardError; end
def lock(&block)
  # 10秒以内に終わらない場合はAccessDenied例外が発生
  Timeout::timeout(10) do
    open(File.join(Dir.tmpdir, 'my-application.lock'), 'w') do |f|
      begin
        f.flock(File::LOCK_EX)
        block.call
      ensure
        f.flock(File::LOCK_UN)
      end
    end
  end
rescue Exception => ex
  raise AccessDenied.new('timeout')
end
lock do
  # 排他処理
end
19
19
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
19