A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/sindresorhus/p-mutex below:

sindresorhus/p-mutex: Async mutex lock for managing access to a shared resource

Async mutex lock for managing access to a shared resource

It provides a safe and easy way to ensure that only one operation accesses a particular resource at a time, preventing race conditions and ensuring data integrity.

import Mutex from 'p-mutex';

const mutex = new Mutex();

const sharedArray = [];

async function addToSharedArray(item) {
	await mutex.withLock(async () => {
		const item = await getItem();
		sharedArray.push(item);
	});
}

addToSharedArray('A');
addToSharedArray('B');

Creates a new mutex object.

Automatically manages the lock during the execution of the given task.

It ensures that the mutex is locked before the task executes and automatically releases the lock afterward, even if an error occurs during the execution.

Parameters:

Returns the result of the task function.

Tip

Prefer using this method for most use cases as it handles the complexities of lock management and is less prone to errors. Use the lock and unlock methods directly only when you need more control over the lock management process.

Acquires the lock.

Returns a promise that resolves when the lock has been acquired.

Important

Ensure every .lock() is paired with .unlock(). Use a try...finally block for safe lock management; the finally block ensures the lock is released, even if an error occurs.

Releases the lock.

Indicates whether the mutex is currently locked.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4