-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.js
More file actions
71 lines (67 loc) · 1.46 KB
/
mutex.js
File metadata and controls
71 lines (67 loc) · 1.46 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
/**
* Mutual Exclusion System
*
* @author Eric Pinto
*/
var Mutex = function(lifo) {
/**
* Current lifo configuration (Default: false)
* true : Stack Mode (Last In First Out)
* false: Queue Mode (First In First Out)
* @type Boolean
*/
this.lifo = lifo || false;
/**
* Current Lock status
* @type Boolean
*/
this.locked = false;
/**
* Queue of callbacks to process
* @type Array
*/
this.waitingQueue = [];
};
/**
* Request to execute the "callback" function in a sequencial way
*
* @param Function callback
*/
Mutex.prototype.lock = function(callback)
{
if (this.locked) {
this.waitingQueue.push(callback);
} else {
this.locked = true;
setTimeout(callback, 0);
}
};
/**
* Release the lock and execute the next "callback" function queued
*/
Mutex.prototype.unlock = function()
{
var callback;
if (this.waitingQueue.length) {
if (this.lifo) {
/**
* Stack Mode
* a. [1, 2] <- 3
* b. [1, 2, 3]
* c. [1, 2] -> 3
*/
callback = this.waitingQueue.pop();
} else {
/**
* Queue Mode
* a. [1, 2] <- 3
* b. [1, 2, 3]
* c. 1 <- [2, 3]
*/
callback = this.waitingQueue.shift();
}
setTimeout(callback, 0);
} else {
this.locked = false;
}
};