diff --git a/lib/process_shared/mutex.rb b/lib/process_shared/mutex.rb index 496ed97..e93cc1e 100644 --- a/lib/process_shared/mutex.rb +++ b/lib/process_shared/mutex.rb @@ -20,6 +20,10 @@ module ProcessShared # @return [Mutex] def lock + if locked_by == ::Process.pid + raise ProcessError, "already locked by this process #{::Process.pid}" + end + @sem.wait self.locked_by = ::Process.pid self @@ -37,7 +41,7 @@ module ProcessShared def sleep(timeout = nil) unlock begin - timeout ? sleep(timeout) : sleep + timeout ? Kernel.sleep(timeout) : Kernel.sleep ensure lock end @@ -62,6 +66,7 @@ module ProcessShared raise ProcessError, "lock is held by #{p} not #{::Process.pid}" end + self.locked_by = 0 @sem.post self end diff --git a/spec/process_shared/mutex_spec.rb b/spec/process_shared/mutex_spec.rb index 84869b5..f9a08bb 100644 --- a/spec/process_shared/mutex_spec.rb +++ b/spec/process_shared/mutex_spec.rb @@ -70,5 +70,13 @@ module ProcessShared ::Process.wait(pid) end + + it 'raises exception when locked twice by same process' do + mutex = Mutex.new + + mutex.lock + proc { mutex.lock }.must_raise(ProcessError) + mutex.unlock + end end end