[Python-ideas] Monitor implementation for the stdlib?

Adam Olsen rhamph at gmail.com
Mon Oct 22 08:21:56 CEST 2007

On 10/21/07, Christopher D. Leary <christopher.leary at cornell.edu> wrote:
> I was surprised to find that there is no "monitor construct"
> implementation for the stdlib. I wrote one that I feel is pretty
> Pythonic, and I'd like it to be torn apart :)
> It's fairly well documented -- for most standard monitor use cases you
> can simply inherit the Monitor class and use the Monitor-specific
> condition variables. Hopefully the accompanying examples will also help
> to clarify the usage. They're somewhat silly, but get the idea across.
> As an aside, because this seems to come up in every conversation I've
> had about monitors in python: if I'm not mistaken, monitors are useful
> with or without the GIL :)
> Monitors are nifty tools that make complex synchronization problems
> somewhat simpler (though more serialized). So far as I understand it,
> the GIL provides single-bytecode atomicity, and monitor methods are
> rarely single instructions. Plus, Jython and IronPython don't have a
> GIL, so I would argue that monitors can still be valuable to "Python the
> language" even if you won't allow that they can be valuable to "Python
> the standard implementation".
> Looking forward to hearing everybody's opinions.

My threading extensions to Python (which I still haven't posted) will
provide a Monitor class and use it fairly often.  There's two major
distinctions from what you suggest though:

 * Deadlocks will be detected and broken automatically
 * Entering the monitor will be enforced by the language.  You'll
never need to consult a memory model to determine correctness.  This
makes it more like Concurrent Pascal's monitors or Erlang's actors
than Java's monitors.

However, it won't drop a lock on every method automatically.  You need
a @monitormethod decorator for that.  A method is often *NOT* the
correct granularity to achieve a thread-safe API!  Consider:

l = ... some "thread-safe" list ...
if l:
    x = l.pop()

There's two method calls, so you cannot guarantee the object hasn't
changed between them.  I get the impression this is regarded as a
major mistake in Java's extensive use of monitors - plastering locks
everywhere just isn't good enough.

Adam Olsen, aka Rhamphoryncus

More information about the Python-ideas mailing list