semafy v2.0.4
Semafy
Semafy provides synchronization and concurrency management across execution agents such as web workers and the main thread. It contains a robust set of tools modeled after C++ synchronization primitives, offering control and flexibility for managing shared resources and states.
Features
- Mutexes: Exclusive and shared locking to protect data from concurrent access.
- ConditionVariable: Allows agents (main thread, web workers) to wait for certain conditions to occur.
- Semaphores: Control access to a finite number of resources.
- Error Handling: Specific classes for various lock-related issues, enhancing debuggability and reliability.
- Platform Agnostic: Works in both browser and server-side applications, and generally any environment that supports
SharedArrayBuffer
.
Installation
NPM:
npm install semafy
Yarn:
yarn add semafy
API
Mutex
Mutex: Provides essential mutex operations including
lock
,unlock
, andtryLock
.TimedMutex: A timed variant that supports timed operations including
tryLockFor
andtryLockUntil
.RecursiveMutex: Allows multiple locks from the same agent.
RecursiveTimedMutex: A timed variant that supports timed operations.
SharedMutex: Allows multiple readers or exclusive writer access, facilitating reader-writer scenarios.
SharedTimedMutex: A timed variant that supports timed operations.
Mutex Management
lockGuard(): Locks a mutex before calling a callback function, ensuring the mutex is unlocked afterwards.
SharedLock: Wraps a
SharedLockable
object (e.g.SharedMutex
) to create a shared lock. Calls tolock
,unlock
, etc will acquire a shared lock instead of an exclusive lock.
Condition Variable
- ConditionVariable: Allows agents to wait for specific conditions, tightly integrated with mutexes for state management.
Semaphore
- CountingSemaphore: Manages access to a finite number of resources, allowing multiple entities to hold the semaphore concurrently up to a maximum count.
Errors
- LockError: A generic error related to errors in lock acquisition, release and management.
- OwnershipError: Occurs when attempting to unlock an unacquired mutex.
- RelockError: Occurs when attempting to lock an already acquired mutex. Prevents deadlocks from occurring.
- TimeoutError: Occurs when an operation exceeds a set time, such as when using
tryLockFor
ortryLockUntil
.
Browser Usage
For security reasons, browsers have certain requirements for using shared memory. Please see SharedArrayBuffer > Security Requirements for details.
Contributing
Contributions are welcome! Please submit any bugs, issues, or pull requests to the project's GitHub repository.