Skip to content

Commit 8422a3b

Browse files
committed
Implement ifAvailable option
1 parent 6b0b94b commit 8422a3b

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

lib/locks.js

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,24 +44,35 @@ class Mutex {
4444
this.current = null;
4545
}
4646

47-
enter(callback) {
48-
this.queue.push(callback);
47+
enter(lock) {
48+
this.queue.push(lock);
4949
this.trying = true;
5050
return this.tryEnter();
5151
}
5252

5353
tryEnter() {
5454
if (this.queue.length === 0) return;
5555
const prev = Atomics.exchange(this.flag, 0, LOCKED);
56-
if (prev === UNLOCKED) {
57-
this.owner = true;
58-
this.trying = false;
59-
const lock = this.queue.shift();
60-
this.current = lock;
61-
return lock.callback(lock).then(() => {
62-
this.leave();
63-
});
64-
}
56+
if (prev === LOCKED) return;
57+
this.owner = true;
58+
this.trying = false;
59+
const lock = this.queue.shift();
60+
this.current = lock;
61+
return lock.callback(lock).then(() => {
62+
this.leave();
63+
});
64+
}
65+
66+
enterIfAvailable(lock) {
67+
if (this.owner) return lock.callback();
68+
const prev = Atomics.exchange(this.flag, 0, LOCKED);
69+
if (prev === LOCKED) return lock.callback();
70+
this.owner = true;
71+
this.trying = false;
72+
this.current = lock;
73+
return lock.callback(lock).then(() => {
74+
this.leave();
75+
});
6576
}
6677

6778
leave() {
@@ -70,6 +81,7 @@ class Mutex {
7081
this.owner = false;
7182
this.current = null;
7283
sendMessage({ kind: 'leave', resourceName: this.name });
84+
this.tryEnter();
7385
}
7486
}
7587

@@ -82,6 +94,7 @@ const request = (resourceName, options, callback) => {
8294
resources.set(resourceName, mutex);
8395
sendMessage({ kind: 'create', resourceName, buffer });
8496
}
97+
if (lock.ifAvailable) return mutex.enterIfAvailable(lock);
8598
return mutex.enter(lock);
8699
};
87100

0 commit comments

Comments
 (0)