-
-
Notifications
You must be signed in to change notification settings - Fork 956
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
118 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
export class Mutex { | ||
private tasks: (() => void)[] = [] | ||
private count = 1 | ||
|
||
private sched(): void { | ||
if (this.count > 0 && this.tasks.length > 0) { | ||
this.count-- | ||
let next = this.tasks.shift() | ||
next() | ||
} | ||
} | ||
|
||
public get busy(): boolean { | ||
return this.count == 0 | ||
} | ||
|
||
// tslint:disable-next-line: typedef | ||
public acquire() { | ||
return new Promise<() => void>(res => { | ||
let task = () => { | ||
let released = false | ||
res(() => { | ||
if (!released) { | ||
released = true | ||
this.count++ | ||
this.sched() | ||
} | ||
}) | ||
} | ||
this.tasks.push(task) | ||
process.nextTick(this.sched.bind(this)) | ||
}) | ||
} | ||
|
||
public use<T>(f: () => Promise<T>): Promise<T> { | ||
return this.acquire() | ||
.then(release => { | ||
return f() | ||
.then(res => { | ||
release() | ||
return res | ||
}) | ||
.catch(err => { | ||
release() | ||
throw err | ||
}) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters