Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

threading.Condition vs threading.Event

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.

like image 459
Parker Ault Avatar asked Sep 15 '11 00:09

Parker Ault


People also ask

What is threading event?

A threading. Event object wraps a boolean variable that can either be “set” (True) or “not set” (False). Threads sharing the event instance can check if the event is set, set the event, clear the event (make it not set), or wait for the event to be set.

What is the purpose of a condition object in a threaded application?

What is the purpose of a condition object in a threaded application? The condition object functions as a lock on a resource.

What does a threading lock do?

A lock allows you to force multiple threads to access a resource one at a time, rather than all of them trying to access the resource simultaneously.

How many threads can be executed at a time in Python?

This means that in python only one thread will be executed at a time. By only allowing a single thread to be used every time we run a Python process, this ensures that only one thread can access a particular resource at a time and it also prevents the use of objects and bytecodes at once.


2 Answers

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.

like image 124
donkopotamus Avatar answered Sep 22 '22 21:09

donkopotamus


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()).

like image 22
Eran Friedman Avatar answered Sep 21 '22 21:09

Eran Friedman