-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmutex.ts
More file actions
75 lines (68 loc) · 1.77 KB
/
Copy pathmutex.ts
File metadata and controls
75 lines (68 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// MutexLock is a held lock on an AsyncMutex.
export interface MutexLock extends AsyncDisposable {
// release releases the lock. Idempotent.
release(): void
[Symbol.asyncDispose](): Promise<void>
}
// AsyncMutex implements a mutex that accepts an AbortSignal.
// TS translation of the Go csync.Mutex.
export class AsyncMutex {
private locked = false
private waiters: Array<() => void> = []
// lock attempts to hold a lock on the AsyncMutex.
async lock(signal?: AbortSignal): Promise<MutexLock> {
signal?.throwIfAborted()
if (!this.locked) {
this.locked = true
return this.newLock()
}
return new Promise<MutexLock>((resolve, reject) => {
const waiter = () => {
resolve(this.newLock())
}
this.waiters.push(waiter)
if (signal) {
const onAbort = () => {
const idx = this.waiters.indexOf(waiter)
if (idx !== -1) {
this.waiters.splice(idx, 1)
}
reject(signal.reason)
}
if (signal.aborted) {
onAbort()
return
}
signal.addEventListener('abort', onAbort, { once: true })
}
})
}
// tryLock attempts to hold a lock on the AsyncMutex.
// Returns a MutexLock or null if the lock could not be grabbed.
tryLock(): MutexLock | null {
if (this.locked) {
return null
}
this.locked = true
return this.newLock()
}
private newLock(): MutexLock {
let released = false
const release = () => {
if (released) return
released = true
this.locked = false
const next = this.waiters.shift()
if (next) {
this.locked = true
next()
}
}
return {
release,
async [Symbol.asyncDispose]() {
release()
},
}
}
}