liveBook · Manning

Semaphore

As explained in Software Design for Python Programmers

A Python Semaphore object controls concurrent access by maintaining a counter of available permits.

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.
A diagram of a diagram

AI-generated content may be incorrect.

The shared-meter diagram shows why writers require exclusion while multiple readers can proceed together. section 16.3.1

How Software Design for Python Programmers covers it

How deep it goes
Explains permit counting, blocking, releasing, and reader-writer coordination through a worked Python simulation; defers broader performance concerns.
Examples
Uses a meter, technician writer threads, logger reader threads, Lock, Semaphore(3), simulated delays, and timestamped output.
What it assumes
Assumes threads, shared resources, critical regions, and mutexes; contrasts semaphore behavior with Lock-based mutual exclusion.
What you can do after
Apply it via Python's threading module to limit simultaneous readers and protect shared resources from concurrent writes.
How it connects
Connects semaphores with mutexes, critical regions, reader-writer problems, deadlocks, race conditions, and Python threading.

Also explained in

Compare how 5 books explain semaphore →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.