On this page
threading.Semaphore
Prev: threading.RLock | Up: threading | Next: threading.setprofile
Rel: threading.active_count, threading.Barrier, threading.BoundedSemaphore, threading.BrokenBarrierError
Ref: docs.python.org โ threading.Semaphore
Tags: #public #python3 #stdlib #threading
Import
import threading
from threading import Semaphore
Signature & Overview
threading.Semaphore(value=1)
This class implements semaphore objects.
Methods & Attributes
Semaphore.acquire(self, blocking=True, timeout=None)โ Acquire a semaphore, decrementing the internal counter by one.Semaphore.release(self, n=1)โ Release a semaphore, incrementing the internal counter by one or more.
Usage
import threading
pool_limit = threading.Semaphore(2)
with pool_limit:
assert True
Gotchas
- Prefer
BoundedSemaphorefor resource pools: PlainSemaphoreallows.release()past the initial count, which is useful for producer/consumer signaling but hides bugs in pool limiting.
REPL Inspect
from threading import Semaphore
help(Semaphore)
Linked from
Related notes
- tuts/python3/stdlib_module/threading/RLock Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/setprofile Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/active_count Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Barrier Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BoundedSemaphore Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BrokenBarrierError Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Condition shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/current_thread shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/enumerate shared tags: #stdlib, #threading