Conditions vs Events

Sergei Organov osv at javad.com
Thu Apr 20 04:59:16 EDT 2006


"Carl J. Van Arsdall" <cvanarsdall at mvista.com> writes:
> Le Monde De Python,
>
> I've been working a lot with python threads from the threading module.  
> Specifically, when is it better to use a condition object vs an event 
> object?

Condition is the universal primitive for waiting for some condition to
occur (and for signalling the condition), where particular "condition"
is defined by your program and not by the primitive itself.

Event, on the other hand, is rather specialized object that allows for,
well, what is written in its documentation, and I fail to see how it
could be used for waiting for an arbitrary condition reliably,
especially when multiple threads can change the condition. Maybe it's
indeed safe in the current Python implementation utilizing GIL, I don't
know, but I'd avoid to use event to be on the safe side anyway.

Overall, everything you can do using event you can do using condition as
well (as you can easily implement your own "event" using condition), but
not vise versa, I'm afraid.

> It seems to me that, at least superficially, I can just about use these 
> two mechanisms interchangeably.

No, in general I don't think you can use event for every purpose for
which condition is appropriate.

> The only real difference I can see is that I can call isSet() on an
> event in the case that an event is triggered before wait() is called.
> Are there any differences?

Well, these two things are so different that I'd instead ask for
similarities, not for differences. The only similarity I see is
existence of wait() method, but even then the semantics of this method
is very different on event and on condition, e.g., condition.wait()
never returns immediately.

BTW, in the case of condition, you not only can, but should check your
own condition before you enter wait, and you should do it in a loop,
otherwise you'll most probably have racy program (e.g., see example at
<http://www.python.org/doc/lib/condition-objects.html>). Obviously,
nobody prevents you from checking your own condition whenever you wish,
and this check is somewhat similar to calling isSet() on an event.

> Also, does calling wait reset some type of "notify" in a condition 
> object like it does in an event object?

No, condition object in this respect is stateless, and notify() never
affects those threads that aren't in the wait queue of the condition at
the moment of "notify" call, i.e., unlike event, condition has no
"memory", so there is nothing inside to be reset by the wait().

However, as far as I can see, event.wait() doesn't change internal state
of the event either. BTW, that's drastically different from how "events"
(called also "signals") work in many of real-time systems, and this may
confuse those who are used to different behavior.

-- Sergei.




More information about the Python-list mailing list