Skip to content

Commit

Permalink
feat: simple SynchronizedLock
Browse files Browse the repository at this point in the history
  • Loading branch information
Siykt committed Oct 21, 2023
1 parent 32bc605 commit d50d596
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/content/synchronizedLock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class SynchronizedLock {
constructor() {
this.lock = false;
this.queue = [];
}

async getLock(timeout = 10000) {
while (this.lock) {
await new Promise((resolve) => {
this.queue.push(resolve);
setTimeout(() => {
const index = this.queue.indexOf(resolve);
if (index !== -1) {
this.queue.splice(index, 1);
console.warn('SynchronizedLock timeout');
resolve();
}
}, timeout);
});
}

this.lock = true;
}

releaseLock() {
this.lock = false;
const resolve = this.queue.shift();
if (resolve) resolve();
}
}

const synchronizedLock = new SynchronizedLock();

export default synchronizedLock;

0 comments on commit d50d596

Please sign in to comment.