Reusable ways to wrapping thread locking techniques

Cameron Simpson cs at
Mon Aug 15 19:37:21 EDT 2011

On 15Aug2011 13:56, python at <python at> wrote:
| I'm reviewing a lot of code that has thread acquire and release
| locks scattered throughout the code base.
| Would a better technique be to use contextmanagers (for safe
| granular locking within a function) or decorators (function wide
| locks) to manage locks or am I making things too complicated?

No, you're on the money.

| Am I reinventing the wheel by creating my own versions of above
| or are there off-the-shelf, debugged versions of above that one
| can use?

I routinely have:

  some_lock = allocate_lock()
  with some_lock:
    code here!

Doing the equivalent with decorators to make monitors seems perfectly
reasonable to me too.

Do it all with context managers if you can; they do reliable lock
release even when an exception occurs, and don't clutter the code with
distracting and hard to verify cleanup code.

It's worth it just to make everything more readable. The fact that it
makes the code smaller and easier to maintain and less bug prone is just

Cameron Simpson <cs at> DoD#743

My mind is like a blotter: Soaks it up, gets it backwards.

More information about the Python-list mailing list