mirror of
https://github.com/vector-im/hydrogen-web.git
synced 2024-12-23 03:25:12 +01:00
some Lock refactoring that I didn't end up needing but still useful
This commit is contained in:
parent
f13f1cd593
commit
89c66699d7
@ -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;
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user