Python Glossary Русский

all Python 3threadingterm

threading.Semaphore

synchronization

A semaphore bounds how many threads may run a block of code at the same time. Useful for limiting parallel requests.

Syntax

sem = threading.Semaphore(n)
with sem: ...

A plain Semaphore keeps no upper bound: an extra release() silently raises the limit above the starting n and hides a leaked-permit bug — use BoundedSemaphore, which raises ValueError instead. Semaphore(1) resembles a Lock, but any thread may release it, whereas a Lock expects a matched acquire/release in one place.

Examples

import threading
sem = threading.Semaphore(3)  # не более 3 одновременно
import threading
import time
sem = threading.Semaphore(3)
def task(i):
    with sem:
        print(f'выполняю {i}')
        time.sleep(0.1)
threads = [threading.Thread(target=task, args=(i,)) for i in range(10)]
for t in threads: t.start()
for t in threads: t.join()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy