Created
September 10, 2021 11:00
-
-
Save nitsanavni/6707747c5ce264c980fbeb19f1854a3b to your computer and use it in GitHub Desktop.
synchronization exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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