runtime.sync
¶
Synchronization primitives using pthread
bindings.
Unlike the primitives available in threading
and multiprocessing
, this
module’s primitives can be created from any buffer, including shared memory, and do not
need to be passed through multiprocessing.Process
to be shared. This module is
intended for consumption by runtime.buffer
.
References
pthreads
documentation:https://pubs.opengroup.org/onlinepubs/009695399/basedefs/pthread.h.html
- exception runtime.sync.SyncError(message, errno, **context)¶
Bases:
runtime.exception.RuntimeBaseException
Synchronization error.
- class runtime.sync.Mutex(buf, /, *, shared: bool = True, recursive: bool = True)¶
Bases:
object
A mutex to enforce mutual exclusion among OS threads.
This mutex supports the context manager protocol to acquire and release automatically. This usage is preferred over manually calling
acquire()
andrelease()
, since failing to release the mutex can starve its waiters. Entering the context uses the default acquisition strategy, which is a timed lock.- Parameters
buf – An optional writeable buffer backing this mutex. Must be at least
Mutex.SIZE
bytes large. Any extra bytes after the firstMutex.SIZE
will remain unused. If not provided, this mutex will use statically allocated memory that cannot be shared.shared (bool) – Whether this mutex is to be shared among processes.
recursive (bool) – Whether this mutex may be successfully reacquired. Every acquisition increments an internal counter, which is decremented by every release. The mutex is only released once the counter reaches zero. Attempting to re-acquire a nonrecursive mutex will raise a
SyncError
witherrno.EDEADLK
as the error code. Attempting to re-release an unlocked mutex will also raise aSyncError
witherrno.EPERM
as the error code.
- acquire(*, timeout=1)¶
Attempt to acquire the mutex.
This method selects an acquisition strategy from the value of
timeout
:When
timeout=None
, this method will acquire the mutex with no timeout. Because this strategy can block indefinitely and starve the waiter, it is not recommended.When
timeout=0
, this method will attempt to acquire the mutex using try-lock.When
timeout > 0
, this method performs a timed lock.
- Parameters
timeout (Optional[float]) – Maximum duration (in seconds) to wait to acquire the mutex.
- Raises
ValueError – If the timeout is strictly negative.
SyncError – If the mutex acquisition fails.
- destroy()¶
Destroy the mutex.
After calling this method, the mutex becomes unusable until
initialize()
is called again.
- initialize()¶
Initialize the mutex.
The mutex is not usuable until
initialize()
is called. Only initialize this mutex once across all waiters. Initializing the mutex multiple times without callingdestroy()
is undefined behavior.