A Python Semaphore controls concurrent access by maintaining a counter of available permits. Multiple threads can acquire it while permits remain; acquisition blocks when the counter reaches zero. section 16.3
Use a semaphore when shared-resource access needs a limit rather than strict one-thread-at-a-time exclusion:
- Initialize it with the maximum number of simultaneous readers. section 16.3
- Acquire it before reading and release it after leaving the critical region. section 16.3 section 16.6
- Combine it with a mutex when writers need exclusive access and readers must be excluded during writes. section 16.3.1
Reader–writer meter
A meter is shared by technician threads that set its value and logger threads that read it. A Lock permits only one technician to write, while Semaphore(3) permits up to three loggers to read and log simultaneously. The semaphore prevents a technician from changing the meter while readers hold permits. section 16.3.1
Figure 16.6 Three technicians simultaneously attempt to set the meter’s value. Meanwhile, three loggers attempt to read and log the meter’s current setting. Therefore, the meter is the shared resource. Only one technician at a time should be setting the meter, and no logger should read the meter while a technician is setting it. However, as long as no technician is setting the meter, multiple loggers can be reading it at the same time.
The shared-meter diagram shows why writers require exclusion while multiple readers can proceed together. section 16.3.1




