mutexify

1.4.0 · maintenance · verified Tue Apr 21

mutexify is a lightweight JavaScript library providing a mutex lock mechanism, primarily designed for Node.js environments. It ensures exclusive access to critical sections of code, guaranteeing that requests are processed in the strict order they were made, thereby preventing common race conditions in asynchronous operations. The library offers two main APIs: a traditional callback-based approach for immediate execution and a modern Promise-based alternative for cleaner `async/await` syntax. Currently at version 1.4.0, the package has maintained this version for approximately four years, suggesting a stable but slow release cadence. Its key differentiator lies in its semantic simplicity and strict adherence to ordered access, making it a straightforward and focused choice for basic locking needs without the overhead of more complex concurrency primitives like read/write locks or advanced semaphore features found in other libraries.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the Promise-based API of mutexify, showing how multiple concurrent async operations will acquire and release the lock sequentially, ensuring ordered execution of critical sections.

import mutexify from 'mutexify/promise';

const lock = mutexify();

async function performLockedOperation(id) {
  console.log(`[Op ${id}] Requesting lock...`);
  const release = await lock();
  try {
    console.log(`[Op ${id}] Lock acquired. Performing work...`);
    // Simulate some asynchronous work inside the locked section
    await new Promise(resolve => setTimeout(resolve, Math.random() * 500 + 200));
    console.log(`[Op ${id}] Work finished.`);
  } finally {
    release(); // Ensure the lock is always released
    console.log(`[Op ${id}] Lock released.`);
  }
}

(async () => {
  console.log('Starting concurrent operations...');
  // Schedule multiple operations concurrently to demonstrate mutex behavior
  const operations = Array.from({ length: 5 }, (_, i) => performLockedOperation(i + 1));
  await Promise.all(operations);
  console.log('All operations completed.');
})();

view raw JSON →