# Mutex confusion

**URL:** <https://rubytalk.org/t/mutex-confusion/55874>\
**Category:** ruby-talk\
**Created:** [20 October 2009 14:10 UTC](https://rubytalk.org/t/mutex-confusion/55874 "2009-10-20T14:10:15Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alex\_Young](https://avatars.discourse-cdn.com/v4/letter/a/ee7513/32.png) [@Alex\_Young](https://rubytalk.org/u/Alex_Young)\
**Post date:** [20 October 2009 14:10 UTC](https://rubytalk.org/t/mutex-confusion/55874/1 "2009-10-20T14:10:15Z")

</div>

I'm a little confused by Mutex's behaviour. It doesn't seem right that a  
single thread should be able to block itself:

alex@twentyone:/tmp$ cat thread-block.rb  
require 'thread'

m = Mutex.new

m.synchronize do  
&nbsp;&nbsp;m.synchronize do  
&nbsp;&nbsp;&nbsp;&nbsp;puts "Woo!"  
&nbsp;&nbsp;end  
end

alex@twentyone:/tmp$ ruby thread-block.rb  
thread-block.rb:6:in `synchronize': stopping only thread (ThreadError)  
&nbsp;&nbsp;note: use sleep to stop forever  
&nbsp;&nbsp;from thread-block.rb:6  
&nbsp;&nbsp;from thread-block.rb:5:in `synchronize'  
&nbsp;&nbsp;from thread-block.rb:5

Why does it behave like this? Is it traditional for mutexes (mutices?)  
to be designed this way?

> **···**
>
> --  
> Alex  
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Justin\_Collins](https://avatars.discourse-cdn.com/v4/letter/j/3e96dc/32.png) [@Justin\_Collins](https://rubytalk.org/u/Justin_Collins)\
**Post date:** [20 October 2009 22:44 UTC](https://rubytalk.org/t/mutex-confusion/55874/2 "2009-10-20T22:44:30Z")

</div>

Alex Young wrote:

> I'm a little confused by Mutex's behaviour. It doesn't seem right that a  
> single thread should be able to block itself:
> 
> alex@twentyone:/tmp$ cat thread-block.rb  
> require 'thread'
> 
> m = Mutex.new
> 
> m.synchronize do  
> &nbsp;&nbsp;m.synchronize do  
> &nbsp;&nbsp;&nbsp;&nbsp;puts "Woo!"  
> &nbsp;&nbsp;end  
> end
> 
> alex@twentyone:/tmp$ ruby thread-block.rb  
> thread-block.rb:6:in `synchronize': stopping only thread (ThreadError)  
> &nbsp;&nbsp;note: use sleep to stop forever  
> &nbsp;&nbsp;from thread-block.rb:6  
> &nbsp;&nbsp;from thread-block.rb:5:in `synchronize'  
> &nbsp;&nbsp;from thread-block.rb:5
> 
> Why does it behave like this? Is it traditional for mutexes (mutices?)  
> to be designed this way?
> 
> --  
> Alex  
> &nbsp;&nbsp;  
> As far as "traditional" behavior, it can go either way. Sometimes counting semaphores are used, which may be acquired multiple times and must be released a corresponding number of times. POSIX threads, for example, provide both options. In this case, however, it is just a binary semaphore: either it is locked or not. The Mutex#synchronize call checks if the lock is available. If not (even it is the current thread that locked it), it blocks, as you noticed. That is its defined behavior in Ruby.

-Justin

---

<div class="post-metadata">

**Author:** ![Alex\_Young](https://avatars.discourse-cdn.com/v4/letter/a/ee7513/32.png) [@Alex\_Young](https://rubytalk.org/u/Alex_Young)\
**Post date:** [21 October 2009 06:02 UTC](https://rubytalk.org/t/mutex-confusion/55874/3 "2009-10-21T06:02:49Z")

</div>

Justin Collins wrote:

> Alex Young wrote:
> 
> > &nbsp;&nbsp;&nbsp;&nbsp;puts "Woo!"  
> > Why does it behave like this? Is it traditional for mutexes (mutices?)  
> > to be designed this way?
> > 
> > --  
> > Alex  
> > &nbsp;&nbsp;  
> > As far as "traditional" behavior, it can go either way. Sometimes  
> > counting semaphores are used, which may be acquired multiple times and  
> > must be released a corresponding number of times. POSIX threads, for  
> > example, provide both options. In this case, however, it is just a  
> > binary semaphore: either it is locked or not. The Mutex#synchronize call  
> > checks if the lock is available. If not (even it is the current thread  
> > that locked it), it blocks, as you noticed. That is its defined behavior  
> > in Ruby.

What would be broken if, hypothetically, the mutex behaviour were  
changed not to block if the current thread already holds the lock? Would  
any possible implementation introduce a race condition?

For a bit of background, this came up while writing a (fairly complex)  
Capistrano recipe. Capistrano uses #set and #fetch methods to allow the  
user to give lazily evaluated settings, like this:

&nbsp;&nbsp;&nbsp;&nbsp;set(:foo){File.join(fetch(:deploy\_to),"foo")}  
&nbsp;&nbsp;&nbsp;&nbsp;set(:deploy\_to){"/tmp"}  
&nbsp;&nbsp;&nbsp;&nbsp;puts fetch(:foo) # \<-- this is where the previous two blocks get  
called

#set and #fetch both protect the inner variable in the same mutex (per  
setting key, that is). This bit me when I was trying to set up a lazily  
evaluated hash, like this:

&nbsp;&nbsp;&nbsp;&nbsp;def add\_to\_settings(key,&val)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;set(:hsh, {}) unless exists?(:hsh)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;set(:hsh) do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fetch(:hsh).merge(key =\> val.call)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end

The idea is that I'd build up a stack of procs which would be called  
when, some time later, I called fetch(:hsh), to return a fully merged  
hash. Unfortunately, because the inner fetch tries to synchronize on the  
same mutex that the outer set already holds, this deadlocks. I've had to  
sidestep set and fetch and forego any thread safety because of this, and  
so far it hasn't been a problem.

Given that I've got a workaround, it's more interesting than annoying,  
but I'm intrigued by the design decision.

> **···**
>
> --  
> Alex  
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [21 October 2009 08:45 UTC](https://rubytalk.org/t/mutex-confusion/55874/4 "2009-10-21T08:45:06Z")

</div>

> Justin Collins wrote:
> 
> > Alex Young wrote:
> > 
> > > &nbsp;&nbsp;&nbsp;&nbsp;puts "Woo!"  
> > > Why does it behave like this? Is it traditional for mutexes (mutices?)  
> > > to be designed this way?
> > > 
> > > --  
> > > Alex  
> > > &nbsp;&nbsp;
> > 
> > As far as "traditional" behavior, it can go either way. Sometimes  
> > counting semaphores are used, which may be acquired multiple times and  
> > must be released a corresponding number of times. POSIX threads, for  
> > example, provide both options. In this case, however, it is just a  
> > binary semaphore: either it is locked or not. The Mutex#synchronize call  
> > checks if the lock is available. If not (even it is the current thread  
> > that locked it), it blocks, as you noticed. That is its defined behavior  
> > in Ruby.
> 
> What would be broken if, hypothetically, the mutex behaviour were changed not to block if the current thread already holds the lock? Would any possible implementation introduce a race condition?

You want Monitor or MonitorMixin then. Mutex is just not implemented reentrant (for efficiency reasons I believe), that's all.

$ ruby19 -r monitor -e '[Monitor,Mutex].each {|m|x=m.new;x.synchronize {x.synchronize {puts m}}}'  
Monitor  
\<internal:prelude\>:6:in `lock': deadlock; recursive locking (ThreadError)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from \<internal:prelude\>:6:in `synchronize'  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from -e:1:in `block (2 levels) in \<main\>'  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from \<internal:prelude\>:8:in `synchronize'  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from -e:1:in `block in \<main\>'  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from -e:1:in `each'  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from -e:1:in `\<main\>'

robert@fussel ~  
$

> Given that I've got a workaround, it's more interesting than annoying, but I'm intrigued by the design decision.

See above.

Kind regards

&nbsp;&nbsp;robert

> **···**
>
> On 21.10.2009 08:02, Alex Young wrote:
> 
> --  
> remember.guy do |as, often| as.you\_can - without end  
> [http://blog.rubybestpractices.com/](http://blog.rubybestpractices.com/)

---

<div class="post-metadata">

**Author:** ![Dev\_Guy](https://avatars.discourse-cdn.com/v4/letter/d/ec9cab/32.png) [@Dev\_Guy](https://rubytalk.org/u/Dev_Guy)\
**Post date:** [22 October 2009 00:12 UTC](https://rubytalk.org/t/mutex-confusion/55874/5 "2009-10-22T00:12:31Z")

</div>

Alex Young wrote:

> What would be broken if, hypothetically, the mutex behaviour were changed not to block if the current thread already holds the lock? Would any possible implementation introduce a race condition?

I'm just learning multi-threading with Ruby, don't like what I see, anyways Ruby doesn't support re-entrance with Mutex, it should but doesn't. There would be no adverse effect regrading re-entrance. A thread that owns the mutex should never be blocked, because its thread safe. Other threads would behave just like they do now, they would block on the mutex until it was released by the owning thread. There would be no racing condition, since the code is thread safe.

> **···**
>
> > --  
> > Alex
> 
> --  
> Kind Regards,  
> Rajinder Yadav
> 
> [http://DevMentor.org](http://DevMentor.org)  
> Do Good ~ Share Freely

---

<div class="post-metadata">

**Author:** ![Dev\_Guy](https://avatars.discourse-cdn.com/v4/letter/d/ec9cab/32.png) [@Dev\_Guy](https://rubytalk.org/u/Dev_Guy)\
**Post date:** [22 October 2009 00:22 UTC](https://rubytalk.org/t/mutex-confusion/55874/6 "2009-10-22T00:22:41Z")

</div>

Robert Klemme wrote:

> > What would be broken if, hypothetically, the mutex behaviour were changed not to block if the current thread already holds the lock? Would any possible implementation introduce a race condition?
> 
> You want Monitor or MonitorMixin then. Mutex is just not implemented reentrant (for efficiency reasons I believe), that's all.

I need to find a better source for Ruby multi-threading, did not know about monitors. Great I picked up something new today!

> **···**
>
> > On 21.10.2009 08:02, Alex Young wrote:
> 
> > Kind regards
> > 
> > &nbsp;&nbsp;&nbsp;&nbsp;robert
> 
> --  
> Kind Regards,  
> Rajinder Yadav
> 
> [http://DevMentor.org](http://DevMentor.org)  
> Do Good ~ Share Freely
