From 89c66699d7f889cede4fb4a55314a83d8d050b74 Mon Sep 17 00:00:00 2001 From: Bruno Windels Date: Tue, 10 Nov 2020 11:04:53 +0100 Subject: [PATCH] some Lock refactoring that I didn't end up needing but still useful --- src/utils/Lock.js | 22 ++++++++++++++-------- src/utils/LockMap.js | 6 ++---- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/utils/Lock.js b/src/utils/Lock.js index 6a198097..e133f33c 100644 --- a/src/utils/Lock.js +++ b/src/utils/Lock.js @@ -20,7 +20,7 @@ export class Lock { this._resolve = null; } - take() { + tryTake() { if (!this._promise) { this._promise = new Promise(resolve => { this._resolve = resolve; @@ -30,6 +30,12 @@ export class Lock { return false; } + async take() { + while(!this.tryTake()) { + await this.released(); + } + } + get isTaken() { return !!this._promise; } @@ -52,25 +58,25 @@ export function tests() { return { "taking a lock twice returns false": assert => { const lock = new Lock(); - assert.equal(lock.take(), true); + assert.equal(lock.tryTake(), true); assert.equal(lock.isTaken, true); - assert.equal(lock.take(), false); + assert.equal(lock.tryTake(), false); }, "can take a released lock again": assert => { const lock = new Lock(); - lock.take(); + lock.tryTake(); lock.release(); assert.equal(lock.isTaken, false); - assert.equal(lock.take(), true); + assert.equal(lock.tryTake(), true); }, "2 waiting for lock, only first one gets it": async assert => { const lock = new Lock(); - lock.take(); + lock.tryTake(); let first; - lock.released().then(() => first = lock.take()); + lock.released().then(() => first = lock.tryTake()); let second; - lock.released().then(() => second = lock.take()); + lock.released().then(() => second = lock.tryTake()); const promise = lock.released(); lock.release(); await promise; diff --git a/src/utils/LockMap.js b/src/utils/LockMap.js index f99776cc..a73dee4a 100644 --- a/src/utils/LockMap.js +++ b/src/utils/LockMap.js @@ -24,12 +24,10 @@ export class LockMap { async takeLock(key) { let lock = this._map.get(key); if (lock) { - while (!lock.take()) { - await lock.released(); - } + await lock.take(); } else { lock = new Lock(); - lock.take(); + lock.tryTake(); this._map.set(key, lock); } // don't leave old locks lying around