69

I have yet to find a clear explanation of the differences between Condition and Event classes in the threading module. Is there a clear use case where one would be more helpful than the other? All the examples I can find use a producer-consumer model as an example, where queue.Queue would be the more straightforward solution.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
Parker Ault
  • 3,268
  • 3
  • 22
  • 24

2 Answers2

96

Simply put, you use a Condition when threads are interested in waiting for something to become true, and once its true, to have exclusive access to some shared resource.

Whereas you use an Event when threads are just interested in waiting for something to become true.

In essence, Condition is an abstracted Event + Lock, but it gets more interesting when you consider that you can have several different Conditions over the same underlying lock. Thus you could have different Conditions describing the state of the underlying resource meaning you can wake workers that are only interested in particular states of the shared resource.

tshepang
  • 12,111
  • 21
  • 91
  • 136
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
18

Another subtle difference is that Event's set() affects future calls of wait() (that is, subsequent calls of wait() will return True and won't block until clear() is called), whereas Condition's notify() (or notify_all()) doesn't (subsequent calls of wait() will block till next call of notify()).

Eran Friedman
  • 578
  • 6
  • 9
  • I don't feel like it's a difference per-se. Condition is a combination of a lock and an event (simplistically). You can say the event is auto-reset. But each call to `wait` should be prefaced with testing the "resource" you are using the condition for. – Guy Dec 31 '19 at 20:18