import { Mutex } from "https://deno.land/x/ayonli_jsext@v0.9.72/lock.ts";
import { Mutex } from "https://deno.land/x/ayonli_jsext@v0.9.72/lock.ts";
Mutual Exclusion prevents multiple coroutines from accessing the same shared resource simultaneously.
NOTE:
Currently, the Mutex instance can not be used across multiple threads, but is
considering adding support for parallel
threads.
Examples
Example 1
Example 1
import { Mutex } from "@ayonli/jsext/lock";
import { random } from "@ayonli/jsext/number";
import { sleep } from "@ayonli/jsext/async";
const mutex = new Mutex(1);
async function concurrentOperation() {
using shared = await mutex.lock();
const value1 = shared.value;
await otherAsyncOperations();
shared.value += 1
const value2 = shared.value;
// Without mutex lock, the shared value may have been modified by other
// calls during `await otherAsyncOperation()`, and the following
// assertion will fail.
console.assert(value1 + 1 === value2);
}
async function otherAsyncOperations() {
await sleep(100 * random(1, 10));
}
await Promise.all([
concurrentOperation(),
concurrentOperation(),
concurrentOperation(),
concurrentOperation(),
]);
Constructors
new
Mutex(value: T)Properties
private
[_value]: TMethods
lock(): Promise<Mutex.Lock<T>>
Acquires the lock of the mutex, optionally for modifying the shared resource.