Last active
August 13, 2023 18:12
-
-
Save mschwartz/c2c22c5bfa314748a95f4c248c38a0f9 to your computer and use it in GitHub Desktop.
Javascript cooperative threading
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
# cat ./threads.js&& node ./threads.js | |
const WAIT_TIME = 1000; | |
async function sleep(ms) { | |
await new Promise((resolve) => setTimeout(resolve, ms)) | |
} | |
async function thread(n) { | |
for (;;) { | |
console.log(`${new Date().toLocaleTimeString()} hello from thread #${n}`); | |
await sleep(WAIT_TIME); | |
} | |
} | |
async function main() { | |
thread(1); | |
thread(2); | |
thread(3); | |
for (;;) { | |
console.log(`${new Date().toLocaleTimeString()} hello from main thread`); | |
await sleep(WAIT_TIME); | |
} | |
} | |
main(); | |
console.log('done') | |
11:09:32 AM hello from thread #1 | |
11:09:32 AM hello from thread #2 | |
11:09:32 AM hello from thread #3 | |
11:09:32 AM hello from main thread | |
done | |
11:09:33 AM hello from thread #1 | |
11:09:33 AM hello from thread #2 | |
11:09:33 AM hello from thread #3 | |
11:09:33 AM hello from main thread | |
11:09:34 AM hello from thread #1 | |
11:09:34 AM hello from thread #2 | |
11:09:34 AM hello from thread #3 | |
11:09:34 AM hello from main thread | |
^C | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment