Limit Access and Rendezvous with Semaphores and Barriers
Core idea
A semaphore tracks permits, allowing up to a configured number of simultaneous acquisitions. BoundedSemaphore detects releases beyond the initial capacity. A Barrier releases a fixed number of participants after all reach a phase boundary. They solve different problems: capacity versus rendezvous.
from threading import BoundedSemaphoreslots = BoundedSemaphore(2)with slots: with slots: print(slots.acquire(blocking=False))print(slots.acquire(blocking=False))slots.release()Two occupied permits exhaust capacity; context exits restore them.
Expected output:
FalseTrueSynchronize a phase
from threading import Thread, Barrier, Lockbarrier = Barrier(2)lock = Lock()arrived = []seen = []def worker(n): with lock: arrived.append(n) barrier.wait() with lock: seen.append(len(arrived))workers = [Thread(target=worker, args=(n,)) for n in (1,2)]for t in workers: t.start()for t in workers: t.join()print(sorted(seen))Each worker observes both arrivals after the phase boundary.
Expected output:
[2, 2]Common mistake
A missing barrier participant can block all others; use a suitable timeout and handle BrokenBarrierError in real applications. Release only permits you acquired.
Practice
Add a third worker and adjust the barrier count. Explain why a semaphore of three does not require all three to arrive.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Semaphores and barriers
Check your understanding of semaphores and barriers.
What is printed?
from threading import Semaphores=Semaphore(1)s.acquire()print(s.acquire(blocking=False))s.release()What is printed?
from threading import Barrierb=Barrier(1)print(b.wait())Which primitive bounds simultaneous resource access?
What is required for a normal barrier release?