-
Notifications
You must be signed in to change notification settings - Fork 0
99_Posix_ipc
Warning
This page will not teach you what named semaphores are.
In the vast majority of cases, you should use multiprocessing or threading inter-process communication instead.
You need to install nob.py with ipc extra: nob.py[ipc].
from nob.ipc import NamedSemaphore
sem = NamedSemaphore("/my_semaphore", handle_existence=NamedSemaphore.Flags.LINK_OR_CREATE)The handle_existence parameter controls the behavior regarding the existence of the semaphore:
-
RAISE_IF_EXISTS: Creates a new semaphore, raises an error if it already exists. -
LINK_OR_CREATE: Links to the existing semaphore if it exists. -
RAISE_IF_NOT_EXISTS: Links to the existing semaphore if it exists, raises an error otherwise. -
UNLINK_AND_CREATE: Deletes the existing semaphore and creates a new one.
The semaphore is automatically unlinked when the object is deleted if it was created by this handle. Else, the semaphore is only closed.
The NamedSemaphore object has a similar interface to threading.Semaphore and multiprocessing.Semaphore. You can use acquire and release to wait and post the semaphore, respectively.
The acquire method also accepts:
-
blocking: Whether to block until the semaphore is available. IfFalse, the method will return immediately withTrueif the semaphore was acquired, andFalseotherwise. -
timeout: If provided, the method will block for at mosttimeoutseconds. If the semaphore is not acquired within this time, the method will return False. If not provided, the method will block indefinitely ifblockingis True. Not supported on macOS.
You may release the semaphore multiple times by calling release with n greater than 1.
sem.acquire()
# critical section
sem.release()Or if you don't need all optional parameters for acquiring and releasing the semaphore:
with sem:
# critical sectionPowered by caffeine and uv.
MIT license.