DirtyHairy / async-mutex

A mutex for synchronizing async workflows in Javascript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Option to empty the queue?

itayganor opened this issue · comments

Hi and thanks for this awesome library.

I was wonder if I can empty this._queue somehow. In my app I manage a queue of actions, but sometimes I just want to empty it all out when a drastic event happens (and the old queue is not relevant anymore).

Thanks!

To get rid of all waiting actions in queue, I can do:

while (mutex.isLocked()) {
    mutex.release();
}

It'll empty the queue but execute anything that is waiting to acquire it. I'm looking for something that will absolutely skip all waiting actions.

To get rid of all waiting actions in queue, I can do:

I sometimes really wish I hadn't added that API (mutex.release()) 😛 I can understand, however, that cancelling all pending requests for a mutex can be useful in some situations. But what would you do with the "task" that currently owns the lock?

I think the safest thing to do would be reject all pending requests for the mutex, but to keep it locked until the "task" that currently holds the mutex has released it.

Would that help your use case?

That could actually help, yes.

In my app, This functionality is actually needed as a cleanup for the previous session. So the perfect solution for me is to kill the task that currently owns the lock, too. I was thinking about throwing an exception in this case.

a nice solution that could do both is to have a clearAll function that also receives a boolean argument - whether to kill the current task or let it finish.

A specific error could be thrown in this case (ClearAllMutexException ?) so you could catch it specifically using try/catch.

What do you think?

So the perfect solution for me is to kill the task that currently owns the lock, too. I was thinking about throwing an exception in this case.

But that's not possible. Once a "task" has acquired the mutex, there's no way to stop it --- what we just called a "task" is really just a sequence of async execution steps that are scheduled on the event loop (and that hopefully do release the mutex eventually). There is no further interaction with the mutex before it is released in which we could throw.

I think the only thing possible is to reject the promises for all pending locks, and to wait until the current holder of the mutex releases it.

I have released version 0.3.0 on NPM. This now includes a cancel() method on mutexes and semaphores that will reject all pending locks. The currently held lock is not affected, though, so the mutex will still be locked until the current lock is released.