DirtyHairy/async-mutex

Feature request: mutex.tryLock()

Closed this issue · 2 comments

I know this seems rather trivial to implement (I think a mutex.isLocked and a consequent mutex.acquire would do the job).

However, I'm not familiar with the internals of this library.

trylock is a standard function in the posix mutex api (pthread_mutex_trylock), would be nice to have it here, too.

👍 That's a useful feature for the next release.

I have just released version 0.3.0 on NPM. This includes a tryAcquire decorator that implements your desired behaviour:

await tryAcquire(mutex).runExclusive(() => ...);
const release = await tryAcquire(mutex).acquire();

I have opted for using a decorator instead of a new method as the decorator works for mutexes and semaphores alike and preserves the full API.