ZetCode

Python Semaphore

last modified November 29, 2026 Python 3.15

In this article we show how to limit concurrent access to a resource in Python threads with threading.Semaphore and threading.BoundedSemaphore.

A semaphore is a counter of permits. The acquire method takes a permit and decrements the counter; when the counter is zero, acquire blocks until another thread calls release, which returns a permit and increments the counter.

A lock lets one thread at a time into a critical section. A semaphore created with n permits lets in up to n threads. It is used for resources of limited capacity, such as database connections, network sockets, or a rate-limited API. A semaphore created with zero permits works as a signal between threads.

Counting permits

The first program shows the counter without any threads. We take permits with non-blocking calls to acquire, which return False instead of waiting.

permits.py
import threading

sem = threading.Semaphore(3)

for i in range(1, 5):
    print(f'acquire {i}: {sem.acquire(blocking=False)}')

sem.release()
print(f'after a release: {sem.acquire(blocking=False)}')

The semaphore starts with three permits.

print(f'acquire {i}: {sem.acquire(blocking=False)}')

The first three calls succeed. The fourth one fails because no permit is left; a blocking call would wait here. After one release, a permit is available again.

$ python permits.py
acquire 1: True
acquire 2: True
acquire 3: True
acquire 4: False
after a release: True

Limiting concurrent threads

In the next program five threads want to download a file, but only two downloads may run at the same time.

first_semaphore.py
import threading
import time

sem = threading.Semaphore(2)
start = time.perf_counter()
timeline = {}


def download(name):
    with sem:
        begin = time.perf_counter() - start
        time.sleep(0.5)
        end = time.perf_counter() - start
    timeline[name] = (begin, end)


threads = [threading.Thread(target=download, args=(f'file-{i}',))
           for i in range(1, 6)]

for t in threads:
    t.start()

for t in threads:
    t.join()

for name, (begin, end) in sorted(timeline.items()):
    print(f'{name}: {begin:.1f} - {end:.1f} s')

Each download takes half a second. The threads record when they started and finished, and the main thread prints the timeline after all of them end.

with sem:
    begin = time.perf_counter() - start
    time.sleep(0.5)
    end = time.perf_counter() - start

Like a lock, a semaphore is a context manager. The with statement acquires a permit before the block and releases it after the block, also when an exception is raised.

The downloads run in pairs: two at 0 seconds, two at 0.5 seconds, and the last one at 1 second. Waiting threads are woken one at a time as permits come back; the order in which they get them is not guaranteed.

$ python first_semaphore.py
file-1: 0.0 - 0.5 s
file-2: 0.0 - 0.5 s
file-3: 0.5 - 1.0 s
file-4: 0.5 - 1.0 s
file-5: 1.0 - 1.5 s

Measuring the peak

To see the limit at work, we count how many jobs are inside the guarded block at once and remember the highest value.

peak.py
import threading
import time

lock = threading.Lock()
active = 0
peak = 0


def job(sem):
    global active, peak
    with sem:
        with lock:
            active += 1
            peak = max(peak, active)
        time.sleep(0.1)
        with lock:
            active -= 1


def run(permits):
    global peak
    peak = 0
    sem = threading.Semaphore(permits)
    threads = [threading.Thread(target=job, args=(sem,)) for _ in range(10)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print(f'permits: {permits:2}, peak concurrency: {peak:2}')


run(1)
run(3)
run(10)

Ten threads run a job that takes 0.1 seconds. We run them with one, three, and ten permits.

with sem:
    with lock:
        active += 1
        peak = max(peak, active)

The active and peak counters are shared by all threads, so they are updated under a lock. A semaphore with more than one permit does not protect shared data: several threads are inside the block at the same time.

The peak equals the number of permits. A semaphore with one permit behaves like a lock, and a semaphore with as many permits as threads does not limit anything.

$ python peak.py
permits:  1, peak concurrency:  1
permits:  3, peak concurrency:  3
permits: 10, peak concurrency: 10

Acquire with a timeout

The timeout parameter limits how long acquire waits for a permit. When the time runs out, it returns False.

parking.py
import threading
import time

spaces = threading.Semaphore(2)
start = time.perf_counter()


def now():
    return time.perf_counter() - start


def car(name, arrive, stay, patience):
    time.sleep(arrive)
    if not spaces.acquire(timeout=patience):
        print(f'{now():.1f} s  {name}: no space, drives away')
        return
    print(f'{now():.1f} s  {name}: parked')
    time.sleep(stay)
    print(f'{now():.1f} s  {name}: leaves')
    spaces.release()


cars = [('car-1', 0.0, 1.0, 0),
        ('car-2', 0.1, 2.0, 0),
        ('car-3', 0.2, 1.0, 0.3),
        ('car-4', 0.3, 1.0, 1.5)]

threads = [threading.Thread(target=car, args=c) for c in cars]

for t in threads:
    t.start()

for t in threads:
    t.join()

A car park has two spaces. Four cars arrive; each waits for a free space at most patience seconds.

if not spaces.acquire(timeout=patience):
    print(f'{now():.1f} s  {name}: no space, drives away')
    return

Without a permit, the car leaves and must not call release. The third car waits 0.3 seconds and gives up. The fourth car is more patient and gets the space that the first car frees at 1 second.

$ python parking.py
0.0 s  car-1: parked
0.1 s  car-2: parked
0.5 s  car-3: no space, drives away
1.0 s  car-1: leaves
1.0 s  car-4: parked
2.0 s  car-4: leaves
2.1 s  car-2: leaves

BoundedSemaphore

A Semaphore does not remember how many permits it started with. Every release adds a permit, even when no permit was taken. A BoundedSemaphore raises ValueError when a release would push the counter above its initial value.

bounded.py
import threading

plain = threading.Semaphore(2)
bounded = threading.BoundedSemaphore(2)

for sem in (plain, bounded):
    name = type(sem).__name__
    sem.acquire()
    sem.release()
    try:
        sem.release()
        print(f'{name}: extra release accepted')
    except ValueError as e:
        print(f'{name}: ValueError: {e}')

Both semaphores start with two permits. Each takes one, returns it, and then returns one more.

sem.release()
print(f'{name}: extra release accepted')

The plain semaphore now has three permits, one more than intended, and from now on lets three threads in. The bounded semaphore refuses the extra release.

$ python bounded.py
Semaphore: extra release accepted
BoundedSemaphore: ValueError: Semaphore released too many times

Catching a release bug

Extra releases are usually bugs, for example a release on an early-return path that is also covered by a finally clause. A bounded semaphore turns such a bug into an error at the place where it happens.

release_bug.py
import threading

sem = threading.BoundedSemaphore(2)


def fetch(url):
    sem.acquire()
    try:
        if not url.startswith('https://'):
            sem.release()
            return f'{url}: rejected'
        return f'{url}: fetched'
    finally:
        sem.release()


for url in ('https://example.com', 'http://example.com'):
    try:
        print(fetch(url))
    except ValueError as e:
        print(f'{url}: ValueError: {e}')

The fetch function rejects plain HTTP URLs.

if not url.startswith('https://'):
    sem.release()
    return f'{url}: rejected'

The early return releases the permit, and the finally clause releases it again. With a plain semaphore the program would silently allow more fetches at once after every rejected URL. When a semaphore guards a resource of fixed size, use BoundedSemaphore.

$ python release_bug.py
https://example.com: fetched
http://example.com: ValueError: Semaphore released too many times

Signalling with a semaphore

A semaphore does not have to start with permits. Created with zero, it counts events: one thread calls release when something is ready, and another thread blocks in acquire until it is. Unlike an RLock, a permit may be released by a different thread than the one that acquires it.

items.py
import collections
import threading
import time

orders = collections.deque()
available = threading.Semaphore(0)


def kitchen():
    for dish in ('soup', 'pasta', 'salad'):
        time.sleep(0.3)
        orders.append(dish)
        print(f'kitchen: {dish} ready')
        available.release()


def waiter():
    for _ in range(3):
        available.acquire()
        dish = orders.popleft()
        print(f'waiter: serving {dish}')


threads = [threading.Thread(target=waiter), threading.Thread(target=kitchen)]

for t in threads:
    t.start()

for t in threads:
    t.join()

A kitchen thread prepares three dishes and a waiter thread serves them. The semaphore counts the dishes that are ready but not yet served.

orders.append(dish)
print(f'kitchen: {dish} ready')
available.release()

The kitchen first adds the dish to the deque and then releases a permit. The order matters: the waiter must not wake up before the dish is there. The append and popleft methods of a deque are thread-safe, so no lock is needed here.

available.acquire()
dish = orders.popleft()

The waiter starts first and blocks until a dish is ready. In real programs queue.Queue does this bookkeeping for us; the example shows the mechanism behind it.

$ python items.py
kitchen: soup ready
waiter: serving soup
kitchen: pasta ready
waiter: serving pasta
kitchen: salad ready
waiter: serving salad

Releasing several permits

Since Python 3.9 the release method takes an argument n and returns n permits at once. With a semaphore that starts at zero, this makes a start gate for a group of threads.

start_gate.py
import threading
import time

gate = threading.Semaphore(0)
start = time.perf_counter()


def runner(name):
    print(f'{name}: ready')
    gate.acquire()
    print(f'{name}: running at {time.perf_counter() - start:.1f} s')


threads = [threading.Thread(target=runner, args=(f'runner-{i}',))
           for i in range(1, 4)]

for t in threads:
    t.start()

time.sleep(0.5)
print('starter: go!')
gate.release(3)

for t in threads:
    t.join()

Three runners get ready and wait at the gate. After half a second the starter lets all of them go.

gate.release(3)

One call wakes up three waiting threads. All runners start at 0.5 seconds; the order of the last three lines can differ between runs. If the gate must wait until all runners are ready, a barrier is the better tool.

$ python start_gate.py
runner-1: ready
runner-2: ready
runner-3: ready
starter: go!
runner-1: running at 0.5 s
runner-3: running at 0.5 s
runner-2: running at 0.5 s

A connection pool

A pool of reusable objects combines a semaphore with a lock. The semaphore counts the free objects and makes threads wait when there are none; the lock protects the list that holds them.

conn_pool.py
import threading
import time


class Pool:

    def __init__(self, size):
        self._free = [f'conn-{i}' for i in range(1, size + 1)]
        self._sem = threading.BoundedSemaphore(size)
        self._lock = threading.Lock()

    def get(self):
        self._sem.acquire()
        with self._lock:
            return self._free.pop()

    def put(self, conn):
        with self._lock:
            self._free.append(conn)
        self._sem.release()


pool = Pool(2)
used = {}


def query(n):
    conn = pool.get()
    try:
        time.sleep(0.2)
        used[n] = conn
    finally:
        pool.put(conn)


threads = [threading.Thread(target=query, args=(n,)) for n in range(6)]

for t in threads:
    t.start()

for t in threads:
    t.join()

print(f'connections used: {sorted(set(used.values()))}')
print(f'queries done: {len(used)}')

Six queries share a pool of two connections. Strings stand in for real database connections.

def get(self):
    self._sem.acquire()
    with self._lock:
        return self._free.pop()

After acquire succeeds, the list is guaranteed to contain a connection, so pop cannot fail. The list itself still needs the lock, because two threads may take connections at the same time.

def put(self, conn):
    with self._lock:
        self._free.append(conn)
    self._sem.release()

The connection goes back to the list before the permit is released. The query function returns the connection in a finally clause, so a failing query does not leak it.

$ python conn_pool.py
connections used: ['conn-1', 'conn-2']
queries done: 6

Bounding submitted tasks

The ThreadPoolExecutor limits the number of worker threads, but not the number of submitted tasks: every submit call adds a task to an unbounded queue. When the tasks come from a large file or a network stream, the queue can use a lot of memory. A semaphore makes the producer wait instead.

bounded_submit.py
import concurrent.futures
import threading
import time

MAX_PENDING = 4

slots = threading.BoundedSemaphore(MAX_PENDING)
lock = threading.Lock()
pending = 0
peak = 0
total = 0


def process(n):
    time.sleep(0.05)
    return n * n


def done(future):
    global pending, total
    with lock:
        pending -= 1
        total += future.result()
    slots.release()


with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
    for n in range(100):
        slots.acquire()
        with lock:
            pending += 1
            peak = max(peak, pending)
        executor.submit(process, n).add_done_callback(done)

print(f'sum of squares: {total}')
print(f'most tasks pending at once: {peak}')

We submit 100 tasks to a pool of two workers, but allow at most four tasks to be pending, that is, submitted and not yet finished.

slots.acquire()
...
executor.submit(process, n).add_done_callback(done)

The main thread takes a permit before each submit and blocks when four tasks are pending.

def done(future):
    global pending, total
    with lock:
        pending -= 1
        total += future.result()
    slots.release()

The callback runs when a task finishes. It adds the result to the total and returns the permit. The program never holds more than four tasks in memory, however many it processes.

$ python bounded_submit.py
sum of squares: 328350
most tasks pending at once: 4

Source

threading — Semaphore objects
threading — BoundedSemaphore

In this article we have limited concurrent access in Python threads with Semaphore and BoundedSemaphore. We have used permits and timeouts, caught release bugs, signalled between threads, released several permits at once, and built a connection pool and a bounded task producer. A semaphore for coroutines is shown in the asyncio article. Protecting shared data is covered in Lock, and making threads wait for each other in Barrier.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.