Martin Andersson
Martin Andersson

Reputation: 1811

Does a Python threading.Condition.wait() suspend execution immediately?

If I call wait() on a python condition variable, does the calling thread suspend execution and yield or does it keep blocking until the next context switch?

Upvotes: 0

Views: 1683

Answers (2)

Matt Joiner
Matt Joiner

Reputation: 118590

The thread does yield. This yielding is due to the implementation of pthread_cond_wait or the equivalent suspension mechanism in in PyThread_acquire_lock. Since the condition variable is implemented using the system call interface, and Python uses native threading, the operating system scheduler is responsible for switching to another thread.

Additionally, the GIL is released before calling this deep into Python's internals. Finally the last piece of the puzzle is the call to acquire the lock in threading.Condition.wait.

Upvotes: 2

O.C.
O.C.

Reputation: 6829

The wait() method releases the lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition variable in another thread. Once awakened, it re-acquires the lock and returns. It is also possible to specify a timeout.

It blocks until the condition is notified.

Upvotes: 1

Related Questions