MenTaLguY
1/19/2007 5:49:00 PM
On Fri, 2007-01-19 at 13:03 +0900, Tim Pease wrote:
> Does fastthread allow you to see who has the lock on the mutex?
fastthread is just a re-implementation of the standard API offered by
Mutex, ConditionVariable, Queue and SizedQueue in thread.rb. That isn't
an ability offered by stdlib's Mutex.
> Sync allows you to do this,
Not safely, actually. Why do you need to do that?
> and it allows me to write re-entrant methods much more easily.
Yes, since Sync locks are reentrant, but personally I would avoid Sync
because it has some bugs, memory leaks, and the implementation isn't
very nice generally.
If do you need both a reentrant lock and the ability to see who's
currently holding it, what I'd suggest instead is writing your own lock
class along these lines:
class MyLock
def initialize
@lock = Mutex.new
@ready = ConditionVariable.new
@count = 0
end
def lock
@lock.synchronize do
@ready.wait @lock while @owner and @owner != Thread.current
@owner = Thread.current
@count += 1
end
self
end
def unlock
@lock.synchronize do
return self unless @owner
@count -= 1
if @count.zero?
@owner = nil
@ready.signal
end
end
self
end
# safely pass the current holder of the lock to a block
def with_locker
@lock.synchronize { yield @owner }
end
end
The above code should work fine with or without fastthread. fastthread
would just make it a little faster (I'd recommend making it an optional
require, as described in the announcement).
I'd strongly recommend against writing code which checks the current
owner of a lock, by the way, but if you really need to do it (I don't
know your specific requirements), something like MyLock#with_locker is
probably the safest way to do so.
-mental