From: Justin Collins Date: 2009-10-21T07:44:30+09:00 Subject: Re: Mutex confusion 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 > m.synchronize do > puts "Woo!" > end > end > > alex@twentyone:/tmp$ ruby thread-block.rb > thread-block.rb:6:in `synchronize': stopping only thread (ThreadError) > note: use sleep to stop forever > from thread-block.rb:6 > from thread-block.rb:5:in `synchronize' > from thread-block.rb:5 > > Why does it behave like this? Is it traditional for mutexes (mutices?) > to be designed this way? > > -- > Alex > 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