ide / await-lock

Mutex locks for async functions
MIT License
89 stars 12 forks source link

Allow having multiple locks with different keys #34

Closed kasbah closed 1 year ago

kasbah commented 1 year ago

This lets you do:

await lock.acquireAsync({key: 'foo'})
await lock.acquireAsync({key: 'bar'})
await lock.release({key: 'foo'})
...
ide commented 1 year ago

It looks like this use case could be addressed in user space by creating a map with multiple locks. IME, lock libraries provide single locks.

kasbah commented 1 year ago

That's true, in fact I've done it that way. I just thought it would be neater if this library provides the mechanism. Here's my implementation in case it's useful to someone.

import AwaitLock from 'await-lock'

const locks = {}

async function acquireLock(key: string): Promise<void> {
  if (!Object.keys(locks).includes(key)) {
    locks[key] = new AwaitLock()
  }
  await locks[key].acquireAsync()
}

async function releaseLock(key: string): Promise<void> {
  if (!Object.keys(locks).includes(key)) {
    console.warn('Releasing unknown lock:', key)
    return
  }
  await locks[key].release()
}

Are you set on not adding this functionality to this lib then?

ide commented 1 year ago

I'd rather keep the API surface area small and leave behavior that can be reasonably implemented in user space out of the library, especially APIs that aren't common to several established lock APIs (Java, Python, POSIX, etc.).