threading.RLock not subclassible?

Tim Peters tim.one at home.com
Mon Feb 5 02:22:23 CET 2001


[John Gault, or maybe George Young]
> I would like to make a subclass of threading.RLock so I can
> add a 'safe_acquire' method.  Safe_acquire would use non-
> blocking acquires and sleeps over several iterations to try
> to acquire the lock, but would eventually return so my thread
> is not forever blocked.
>
> But the RLock class seems to be written in a way discouraging
> subclassing:
> ...
> It looks like the author(not identified in the code) is explictly
> trying to avoid subclassing...

The author is Guido Himself, and he was indeed trying to avoid subclassing.
I didn't know why either, but had a chance ask him.  The deal is that some
platforms may have a much more efficient way to implement one or more of
these abstractions, in which case threading.py would be happy to export the
platform-specific way when running on that platform.

There are no instances of that yet, although threading.py gets kinda close
with its

Lock = _allocate_lock

You can't subclass from Lock because its *implementation*
(thread.allocate_lock) is not a class.  The same may well be true of future
platform-specific implementations of synch objects.  So threading.py exposes
factory functions instead of classes.

There's no immediate danger that you'll get in trouble by subclassing from
_RLock instead, but there's no guarantee that will remain safe (the leading
underscore means, as you know, "touch at your own risk").

BTW, an acquire with a timeout is a cool idea!  Feel encouraged to submit a
patch to add such a thing directly to threading.py:

    http://sourceforge.net/patch/?group_id=5470

I suggest a name like timed_acquire, though -- if it's in the core, the name
safe_acquire reads more like a snotty value judgment about the other
.acquire() <wink>.

safety-depends-more-on-how-it's-used-than-what-it-does-ly y'rs  - tim






More information about the Python-list mailing list