Skip to content

Instantly share code, notes, and snippets.

@mschwartz
Last active August 13, 2023 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mschwartz/c2c22c5bfa314748a95f4c248c38a0f9 to your computer and use it in GitHub Desktop.
Save mschwartz/c2c22c5bfa314748a95f4c248c38a0f9 to your computer and use it in GitHub Desktop.
Javascript cooperative threading
# 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