Locks
Locks implements locking/synchronization mechanisms that have traditionally been used for protecting shared memory between multiple threads. JavaScript is inherently single threaded and does not suffer from these security and stability issues. However, because of its asynchronous eventy nature JavaScript can still benefit from making particular operations wait for the completion of others.
Installation
Node.js users:
npm install locks
Component users:
component install Wizcorp/locks
API
Accessing the locks module:
var locks = ;
Please note that all the examples below will also demonstrate how to unlock each time. But in general, this matters:
// unlocking will give waiting processes a chance to get the lock and continuemyLock;
Mutex locks
Mutex locks are the most basic locks which aim to prevent the simultaneous access to a resource by more than one actor at a time. more info
Creating a Mutex Lock:
var mutex = locks;
Waiting to lock:
mutex;
Waiting to lock, with timeout:
mutex;
Optimistic attempt to lock:
if mutex console; // do stuff mutex; else console;
Read/Write locks
Read/Write Locks are used to allow many actors to read from a resource, as long as nothing is writing to it. That also means that only one actor may be writing at any given time. more info
Creating a Read/Write Lock:
var rwlock = locks;
Waiting to read lock:
rwlock;
Waiting to write lock:
rwlock;
Waiting to read lock, with timeout:
rwlock;
Waiting to write lock, with timeout:
rwlock;
Optimistic attempt to read lock:
if rwlock console; // do stuff rwlock; else console;
Optimistic attempt to write lock:
if rwlock console; // do stuff rwlock; else console;
Condition variables
Condition variables allow synchronization between processes based on values.
Creating a Condition Variable:
var initialValue = 'hello world';var cond = locks;
Waiting for a condition to be met:
cond;
Setting the value on a Condition Variable:
cond;
Semaphores
Semaphores solve the problem of sharing a limited set of resources. more info
Creating a Semaphore:
var initialValue = 3; // amount of resources availablevar sem = locks;
Claiming and releasing a resource:
sem;
License
MIT