x-cold / mutex

A javascript mutex lib like the sync.Mutex concurrent primitive of Golang

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mutex

NPM version build status Test coverage npm download

A modern lightweight lib to control the promise mutex

Usage

The version of your node.js should be greater than v12

npm i -S js-mutex

Importing library

import Mutex from 'js-mutex';

async function singleExecute() {
  const mutex = new Mutex();
  let cur = 0;
  await mutex.lock();
  cur = 1;
  await mutex.unlock();
}

async function singleExecuteConcurrency() {
  const mutex = new Mutex();
  const result: number[] = [];

  async function fn(i: number) {
    await mutex.acquire(async () => {
      await sleep(100);
      result.push(i);
    });
  }

  const promises = [];
  for (let i = 0; i < 10; i += 1) {
    promises.push(fn(i));
  }

  await Promise.all(promises);
}

About

A javascript mutex lib like the sync.Mutex concurrent primitive of Golang


Languages

Language:TypeScript 59.4%Language:JavaScript 29.9%Language:Shell 10.7%