35 lines
863 B
JavaScript
35 lines
863 B
JavaScript
'use strict'
|
|
|
|
class AsyncLock {
|
|
constructor() {
|
|
this.queue = []
|
|
this.locked = false
|
|
}
|
|
|
|
acquire(){
|
|
return new Promise((resolve) => {
|
|
if (!this.locked) {
|
|
// No contention, acquire lock immediately
|
|
this.locked = true
|
|
resolve()
|
|
} else {
|
|
// Add to queue when lock is busy
|
|
this.queue.push(resolve)
|
|
}
|
|
})
|
|
}
|
|
|
|
release(){
|
|
if (this.queue.length > 0) {
|
|
// Resolve the next queued promise
|
|
const nextResolve = this.queue.shift()
|
|
nextResolve()
|
|
// Keep locked status as true since we're passing the lock to the next waiter
|
|
} else {
|
|
// No waiters, unlock
|
|
this.locked = false
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = AsyncLock |