28 lines
538 B
TypeScript
28 lines
538 B
TypeScript
////
|
|
// Simple mutex for concurrent file writes
|
|
|
|
export class Mutex {
|
|
private queue: (() => void)[] = []
|
|
private locked = false
|
|
|
|
async lock(): Promise<() => void> {
|
|
return new Promise(resolve => {
|
|
const unlock = () => {
|
|
const next = this.queue.shift()
|
|
if (next) {
|
|
next()
|
|
} else {
|
|
this.locked = false
|
|
}
|
|
}
|
|
|
|
if (this.locked) {
|
|
this.queue.push(() => resolve(unlock))
|
|
} else {
|
|
this.locked = true
|
|
resolve(unlock)
|
|
}
|
|
})
|
|
}
|
|
}
|