Search⌘ K
AI Features

Barrier, Semaphore, Condition Variable

Explore how to implement Barrier, Semaphore, and Condition Variable using Python's multiprocessing module. Understand process synchronization techniques that control execution order and communication between parallel processes.

We'll cover the following...

Barrier, Semaphore, Condition Variable

Semaphore

The multiprocessing.Semaphore is very similar to threading.Semaphore. The only difference is that the acquire() method's first argument is named block instead of blocking as is the case for threading.Semaphore. Below is a simple program between two processes that take turns to write "ping" and "pong" on the console. The script uses multiprocessing.Semaphore initialized to zero. Additionally, we also use a multiprocessing.Value boolean object to indicate to the two processes to exit.

Printing ping and pong

from multiprocessing import Semaphore,
...