API reference / @evolu/common / Task / createMutex

Function: createMutex()

function createMutex(): Mutex;

Defined in: packages/common/src/Task.ts:731

Creates a new mutex for ensuring mutual exclusion.

A mutex is a createSemaphore with exactly one permit, ensuring that only one Task can execute at a time.

Example

const mutex = createMutex();

const updateTask = (id: number) =>
  toTask((context) =>
    tryAsync(
      () => updateSharedResource(id, context),
      (error): UpdateError => ({ type: "UpdateError", error }),
    ),
  );

// These Tasks will execute one at a time
const results = await Promise.all([
  mutex.withLock(updateTask(1))(),
  mutex.withLock(updateTask(2))(),
  mutex.withLock(updateTask(3))(),
]);

Returns

Mutex

Was this page helpful?