forked from shaka-project/shaka-player
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutex.js
59 lines (51 loc) · 1.23 KB
/
mutex.js
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
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.util.Mutex');
goog.require('shaka.log');
/**
* @summary A simple mutex.
*/
shaka.util.Mutex = class {
/** Constructs the mutex. */
constructor() {
/** @private {?string} */
this.acquiredIdentifier = null;
/** @private {!Array<function()>} */
this.unlockQueue = [];
}
/**
* Acquires the mutex, as soon as possible.
* @param {string} identifier
* @return {!Promise}
*/
async acquire(identifier) {
shaka.log.v2(identifier + ' has requested mutex');
if (this.acquiredIdentifier) {
await new Promise((resolve) => this.unlockQueue.push(resolve));
}
this.acquiredIdentifier = identifier;
shaka.log.v2(identifier + ' has acquired mutex');
}
/**
* Releases your hold on the mutex.
*/
release() {
shaka.log.v2(this.acquiredIdentifier + ' has released mutex');
if (this.unlockQueue.length > 0) {
this.unlockQueue.shift()();
} else {
this.acquiredIdentifier = null;
}
}
/**
* Completely releases the mutex. Meant for use by the tests.
*/
releaseAll() {
while (this.acquiredIdentifier) {
this.release();
}
}
};