From: Robert Klemme Date: 2009-10-21T17:45:06+09:00 Subject: Re: Mutex confusion On 21.10.2009 08:02, Alex Young wrote: > Justin Collins wrote: >> Alex Young wrote: >>> puts "Woo!" >>> 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. > > 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 :6:in `lock': deadlock; recursive locking (ThreadError) from :6:in `synchronize' from -e:1:in `block (2 levels) in
' from :8:in `synchronize' from -e:1:in `block in
' from -e:1:in `each' from -e:1:in `
' 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 robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/