Skip to content

Commit

Permalink
Implement ifAvailable option
Browse files Browse the repository at this point in the history
  • Loading branch information
tshemsedinov committed Mar 28, 2019
1 parent 6b0b94b commit 8422a3b
Showing 1 changed file with 24 additions and 11 deletions.
35 changes: 24 additions & 11 deletions lib/locks.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,35 @@ class Mutex {
this.current = null;
}

enter(callback) {
this.queue.push(callback);
enter(lock) {
this.queue.push(lock);
this.trying = true;
return this.tryEnter();
}

tryEnter() {
if (this.queue.length === 0) return;
const prev = Atomics.exchange(this.flag, 0, LOCKED);
if (prev === UNLOCKED) {
this.owner = true;
this.trying = false;
const lock = this.queue.shift();
this.current = lock;
return lock.callback(lock).then(() => {
this.leave();
});
}
if (prev === LOCKED) return;
this.owner = true;
this.trying = false;
const lock = this.queue.shift();
this.current = lock;
return lock.callback(lock).then(() => {
this.leave();
});
}

enterIfAvailable(lock) {
if (this.owner) return lock.callback();
const prev = Atomics.exchange(this.flag, 0, LOCKED);
if (prev === LOCKED) return lock.callback();
this.owner = true;
this.trying = false;
this.current = lock;
return lock.callback(lock).then(() => {
this.leave();
});
}

leave() {
Expand All @@ -70,6 +81,7 @@ class Mutex {
this.owner = false;
this.current = null;
sendMessage({ kind: 'leave', resourceName: this.name });
this.tryEnter();
}
}

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

Expand Down

0 comments on commit 8422a3b

Please sign in to comment.