DirtyHairy / async-mutex

A mutex for synchronizing async workflows in Javascript
MIT License
1.14k stars 63 forks source link

mutex.waitForUnlock() bug? #52

Closed ricardojosegomezulmke closed 2 years ago

ricardojosegomezulmke commented 2 years ago

Not sure if this is a bug or if I'm using it incorrectly.

version: 0.3.2 node: v16.6.1 typescript: Version 4.5.5

const myMutex = new Mutex();

await myMutex.runExclusive( async () => { await myAsyncFunc(); });

// now wait until unlocked ... await myMutex.waitForUnlock(); if(myMutex.isLocked()) throw new Error('myMutex is locked'); // <== this throws the error all the time

// instead, this works fine const releaser = await myMutex.acquire(); releaser(); if(myMutex.isLocked()) throw new Error('myMutex is locked); // <== never throws, it works

BTW, awesome library!

DirtyHairy commented 2 years ago

Sorry for the late reply. Indeed, you're right, I checked the code, if there are more tasks blocked in the queue, then the semaphore will have decremented again before the waiter is resolved. This will still happen at the correct time (after the previous task has released the mutex and before the next task has acquired it, but this is not reflected by isLocked() --- this only evaluates to true if no more tasks are waiting to acquire the mutex.

I'll add a fix in the next release.

nklhtv commented 2 years ago

i am facing the same issue what i do for now is replacing await mutex.waitForUnlock(); with await mutex.acquire().then((release) => release()); .... awesome library btw!!!

DirtyHairy commented 2 years ago

Fixed in 0.4.0