tim.one at home.com
Wed Mar 14 09:18:13 CET 2001
> I'm using the threading module, with the Event class to handle
> synchronisation. It's all working nicely and is very easy to use.
> However, I can't seem to find a way of atomically waiting for an Event,
> and then clearing the flag, which is very strange. Currently I do
> Event.wait() and then Event.clear(). If another thread does a Event.set()
> in between the two, the event will be lost. For my current application,
> this isn't a problem, but what shold I do in the future?
Use a more appropriate synch mechanism. Events are usually one-shot
broadcast mechanisms. For example, in a multi-pass algorithm over a giant
array, send 10 threads off to do the first pass, then when each is done have
each wait for the "first pass is done; move on to the second pass" Event.
This doesn't work, though, if any thread clears the event before all have
seen it. Most times an Event never gets cleared, and (as you've discovered!)
it's quite tricky to do so safely in any but trivial cases.
Hard to guess what you're doing, but it sounds like you're using an Event as
a "hey, there's something to do!" signal, where there will be something to do
more than once over the life of your job. If so, a Condition is very good
for that: the Condition protocol .notify and .wait occur under the
protection of a mutex, so after a thread T does a successful
Condition.wait(), no thread can do another Condition.notify() before T does
Condition.release() (the *reason* no other thread can do another
Condition.notify() is that they have to do a Condition.acquire() first, but
before T does its .release() all other threads will block on the .acquire()).
luckily-it's-easier-to-use-than-to-explain<wink>-ly y'rs - tim
More information about the Python-list