Skip to content

Instantly share code, notes, and snippets.

@brandonbloom
Created July 14, 2020 17:10
Show Gist options
  • Save brandonbloom/8d4fc558537492432bf16c529b937e32 to your computer and use it in GitHub Desktop.
Save brandonbloom/8d4fc558537492432bf16c529b937e32 to your computer and use it in GitHub Desktop.
let mutex = Promise.resolve();
let counter = 0;
const read = async () => counter;
const write = async (value) => {
counter = value;
}
const sleep = (ms) =>
new Promise(accept => setTimeout(accept, ms));
const criticalSection = async (f) => {
mutex = mutex.then(f);
await mutex;
}
const numWorkers = 200;
const incsPerWorker = 3000;
const expected = numWorkers * incsPerWorker;
const worker = async () => {
for (let i = 0; i < incsPerWorker; i++) {
await criticalSection(async () => {
let x = await read();
await sleep(Math.random() * 50);
await write(x + 1);
});
}
};
const main = async () => {
const workers = [];
for (let i = 0; i < numWorkers; i++) {
workers.push(worker());
}
await Promise.all(workers);
if (expected === counter) {
console.log('ok');
} else {
console.log('expected:', expected);
console.log('got:', counter);
}
};
void main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment