Use of threading.Condition class
Tim Peters
tim.one at home.com
Fri Jan 5 03:05:29 EST 2001
[vonWedel at lfpt.rwth-aachen.de]
> I'm trying to pass data between threads A and B. A notifies B
> to produce something and now I want the reference to the
> produced instance back in thread A. The documentation for
> threading.Condition proposes something like
>
> # Consume one item
> cv.acquire()
> while not an_item_is_available():
> cv.wait()
> get_an_available_item()
> cv.release()
>
> for the consumer side. I don't understand the while loop around
> the cv.wait() statement -- wouldn't cv.wait() block anyway until
> cv.notify() has been called in the other thread?
Do yourself a favor, and write it that way whether you understand it or not
<0.1 wink>.
You've only got two threads today. Tomorrow you may have one producer and
two consumers. Then the loop is essential, else e.g. consumer 1 and
consumer 2 could both say "aha! there's something in the queue!" after a
single item was entered. One of them would get it, and the other one would
blow up. The loop is also essential in a two-thread world if the producer
may change its mind about whether something is available. Writing it with a
loop, as suggested, makes it robust against all sorts of modifications in
the future.
If all you will ever have is two threads, and all you will ever pass is one
thing at a time, then a simpler mechanism (like an Event) could suffice.
Also look at the docs for the std Queue module, which supplies a long-tested
inter-thread queueing mechanism already written for you.
running-in-a-loop-prevents-you-from-falling-off-the-cliff-ly y'rs
- tim
More information about the Python-list
mailing list