Skip to content

99_Posix_ipc

Thomas Byr edited this page May 25, 2026 · 4 revisions

Named Semaphores python bridge

  1. Creation
  2. Post and wait

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].

Creation

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.

Post and wait

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. If False, the method will return immediately with True if the semaphore was acquired, and False otherwise.
  • timeout: If provided, the method will block for at most timeout seconds. If the semaphore is not acquired within this time, the method will return False. If not provided, the method will block indefinitely if blocking is 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 section

Clone this wiki locally