Back
+15 XP
Concept

Semaphores: Limiting Concurrent Access

A semaphore manages an atomic counter. While a mutex lock allows only 1 thread, `threading.Semaphore(n)` permits up to `n` concurrent threads to access a resource (e.g. rate-limiting DB pools) 🚥.

python
import threading

# Allow max 2 threads simultaneously:
pool = threading.Semaphore(2)

def access_resource(worker_id):
    with pool:
        print(f"Worker {worker_id} acquired slot 🚥")

threads = [threading.Thread(target=access_resource, args=(i,)) for i in range(3)]
for t in threads: t.start()
for t in threads: t.join()

# 57. Semaphores: Limiting Concurrent Access A semaphore manages an atomic counter. While a mutex lock allows only 1 thread, `threading.Semaphore(n)` permits up to `n` concurrent threads to access a resource (e.g. rate-limiting DB pools) 🚥. ```python import threading # Allow max 2 threads simultaneously: pool = threading.Semaphore(2) def access_resource(worker_id): with pool: print(f"Worker {worker_id} acquired slot 🚥") threads = [threading.Thread(target=access_resource, args=(i,)) for i in range(3)] for t in threads: t.start() for t in threads: t.join() ``` Every time `with pool:` is entered, the counter decrements. When it reaches 0, additional threads wait until an active thread exits and increments the counter! 🚥 --- ### Question How does `threading.Semaphore(3)` differ from `threading.Lock()`? 🧠 - [ ] a. A semaphore allows up to 3 concurrent threads, whereas a lock permits only 1 🚥 - [ ] b. A semaphore only works on async coroutines - [ ] c. A lock cannot be used inside a with statement - [ ] d. Semaphores automatically spawn 3 new processes --- ### Challenge Create a `threading.Semaphore(2)`. Acquire a slot using `with sem:`, inside it print `'Slot granted'`. 🎯 <details> <summary>Solution</summary> ```python import threading sem = threading.Semaphore(2) with sem: print("Slot granted") ``` </details>

Checkpoint

How does `threading.Semaphore(3)` differ from `threading.Lock()`? 🧠

Practice

Create a `threading.Semaphore(2)`. Acquire a slot using `with sem:`, inside it print `'Slot granted'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks