class Mutex

Public Class Methods

new(name, ttl=2.048) click to toggle source

@param [String] name Mutex name. One process at once can gain a lock against a name. @param [Numeric] ttl Time to auto-release a gained lock. @return [Tengine::Core::Mutex] An instance.

# File lib/tengine/core/mutex.rb, line 128
def new name, ttl=2.048
  t = 0.0 + ttl # type check
  raise TypeError, "finite numeric expected (got #{t})" unless t.finite?
  raise ArgumentError, "TTL doesn't make sense." unless t > 0

  return oldnew(Tengine::Core::Mutex::Mutex.find_or_create(name, t), Moped::BSON::ObjectId.new, 0)
end
Also aliased as: oldnew
oldnew(name, ttl=2.048)
Alias for: new

Public Instance Methods

heartbeat() click to toggle source

If you need to lock it longer than ttl, call this and you can refresh the ttl.

# File lib/tengine/core/mutex.rb, line 195
def heartbeat
  mutex.heartbeat self
end
synchronize() { || ... } click to toggle source

delays until you get a lock.

# File lib/tengine/core/mutex.rb, line 175
def synchronize(&block)
  raise ArgumentError, "no block given" unless block_given?

  if lock
    # OK, locked
    EM.schedule do
      begin
        heartbeat
        yield
      ensure
        unlock
      end
    end
  else
    # NG, try again later
    synchronize_internal mutex.ttl, block
  end
end

Private Instance Methods

lock() click to toggle source
# File lib/tengine/core/mutex.rb, line 146
def lock
  if lock_attempt
    self.recursive += 1
  end
end
lock_attempt() click to toggle source
# File lib/tengine/core/mutex.rb, line 139
def lock_attempt
  m = mutex
  m.invalidate
  m.lock self
  return m.waiters.first["_id"] == _id
end
synchronize_internal(ttl, blk) click to toggle source
# File lib/tengine/core/mutex.rb, line 159
def synchronize_internal ttl, blk
  # stop stack consumption
  EM.add_timer ttl do
    begin
      synchronize(&blk)
    rescue Exception => e
      msg = sprintf "%p\n%s", e, e.backtrace.join("\n")
      Tengine.logger.error msg
      # no raise
    end
  end
end
unlock() click to toggle source
# File lib/tengine/core/mutex.rb, line 152
def unlock
  self.recursive -= 1
  if self.recursive <= 0
    mutex.unlock self
  end
end