lib/lusnoc/mutex.rb in lusnoc-0.0.2 vs lib/lusnoc/mutex.rb in lusnoc-0.1.0

- old
+ new

@@ -5,11 +5,11 @@ class Mutex include Helper attr_reader :key, :value, :owner - def initialize(key, value = Socket.gethostname, ttl: 20) + def initialize(key, value: Socket.gethostname, ttl: 20) @key = key @value = value @ttl = ttl end @@ -23,23 +23,28 @@ def session_id @session&.id end - [:time_to_expiration, :need_renew?, :ttl, :expired?, :live?, :live!, :renew].each do |m| + [:time_to_expiration, :need_renew?, :ttl, :expired?, :alive?, :alive!, :renew].each do |m| define_method(m) { @session&.public_send(m) } end + def on_mutex_lost(&block) + @on_mutex_lost = block + end + def synchronize(timeout: 0, &block) timeouter = Timeouter.new(timeout, exception_class: TimeoutError, exception_message: 'mutex acquisition expired') Session.new("mutex_session/#{key}", ttl: @ttl) do |session| @session = session session.on_session_die do @owner = nil + @on_mutex_lost&.call(self) end return acquisition_loop! key, session, value, timeouter, &block ensure release(key, session.id, timeout: 2) rescue nil @@ -68,10 +73,10 @@ def acquisition_loop!(key, session, value, timeouter) return yield(self) if acquire(key, session, value) logger.debug("Start #{key} acquisition loop for session #{session.name}[#{session.id}]") timeouter.loop! do - session.live!(TimeoutError) + session.alive!(TimeoutError) wait_for_key_released(key, timeouter.left) return yield(self) if acquire(key, session, value) logger.debug("Lock #{key} acquisition failed for session #{session.name}[#{session.id}]")