Skip to content

Instantly share code, notes, and snippets.

@nitsanavni
Created September 10, 2021 11:00
Show Gist options
  • Save nitsanavni/6707747c5ce264c980fbeb19f1854a3b to your computer and use it in GitHub Desktop.
Save nitsanavni/6707747c5ce264c980fbeb19f1854a3b to your computer and use it in GitHub Desktop.
synchronization exercise
// helpers
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const rand = (max) => Math.floor(Math.random() * max);
const times = (n, cb) => {
const ret = [];
for (let i = 0; i < n; i++) {
ret.push(cb());
}
return ret;
};
const fun = async ({ sync }) => {
while (true) {
// TODO: implement `syncImpl` such that **all** invocations of `fun`
// wait for each other at this call to `sync()` for all the
// iterations of the while loop
await sync();
await sleep(rand(100));
}
};
const syncImpl = () => {
// implement me
};
// invoke `fun` 10 times
times(10, () => fun({ sync: syncImpl() }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment