Sha256: b7cf0a5f3f1c4f89a21fe9f960b7e34038fb6296e4fa39301570d335e5deccc4

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

require 'socket'
module Mongoid
  module Lock
    
    def reset_lock!
      self.set(:lock_used_by, nil)
    end
    
    def lock_acquire
      local = "#{Socket.gethostname}:#{Process.pid}"
      ident = self.lock_used_by
      if (ident and ident != local)
        raise Mongoid::Lock::UnsynchronizedAccess.new(ident)
      else
        self.set(:lock_used_by, local)
      end
    end
    
    def lock_release
      local = "#{Socket.gethostname}:#{Process.pid}"
      ident = self.lock_used_by
      if (ident and ident == local)
        self.reset_lock!
      else
        raise Mongoid::Lock::UnsynchronizedAccess.new(ident)
      end
    end
    
    def synchronized(&block)
      self.lock_acquire
      begin
        block.call()
      ensure
        self.lock_release
      end
    end
    
    def try_synchronized(&try_block)
      begin
        self.synchronized do
          try_block.call()
        end
        return true
      rescue Mongoid::Lock::UnsynchronizedAccess => ua
        return false
      end
    end
    
    def wait_synchronized(timeout, &block)
      started = Time.now
      expires = started + timeout
      begin
        success = self.try_synchronized do
          block.call()
        end
        unless (success)
          sleep(2)
        end
      end while(not success and Time.now < expires)
      return success
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-lock-0.0.4 lib/mongoid/lock/synch_methods.rb