@esfx/async-mutex
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@esfx/async-mutex

Provides AsyncMutex, an async coordination primitive.

Overview

Installation

npm i @esfx/async-mutex

Usage

import { AsyncMutex } from "@esfx/async-mutex";

const m = new AsyncMutex();
let counter = 0;

async function worker() {
    for (let i = 0; i < 3; i++) {
        // get exclusive access to 'm', which protects 'counter'.
        const lk = await m.lock();
        try {
            const current = counter;

            await doSomethingElse();

            // we still have exclusive access to 'm', which protects 'counter'.
            counter = current + 1;
        }
        finally {
            // release the lock
            lk.unlock();
        }
    }
}

async function main() {
    // start two workers that share a resource
    await Promise.all([worker(), worker()]);

    counter; // 6
}

API

You can read more about the API here.

Readme

Keywords

none

Package Sidebar

Install

npm i @esfx/async-mutex

Weekly Downloads

71

Version

1.0.0

License

Apache-2.0

Unpacked Size

39.1 kB

Total Files

8

Last publish

Collaborators

  • rbuckton