Skip to content

Instantly share code, notes, and snippets.

@jojo2357
Created October 4, 2022 00:19
Show Gist options
  • Save jojo2357/fe8e33abf3a355dbb1e8febd9a07ef19 to your computer and use it in GitHub Desktop.
Save jojo2357/fe8e33abf3a355dbb1e8febd9a07ef19 to your computer and use it in GitHub Desktop.
Nodejs `+=` Race Condition
/*
* Using node v12.19.0 This demonstrates the potential dangers of sync/async.
* This likely will not print 20 ((0 + 1) + (1 + 1) ... + (4 + 1)) = 1 + 2 + 3 + 4 + 5 = 15
*/
/**
* @param arg {number}
* @return {Promise<number>} returns the arg provided after a timeout
*/
function sleep(arg) {
return new Promise((resolve, reject) => {
setTimeout(resolve, 1000 * Math.random(), arg);
});
}
let globalVar = 0;
// swap the comments in order to get expected behavior.
async function thred(args) {
//let add = await sleep(args + 1);
//globalVar += add;
globalVar += await sleep(args + 1);
}
// spawn threads
for (let i = 0; i < 5; i++) {
thred(i);
}
//after everything has resolved, print the var
process.on('exit', () => {
console.log(globalVar);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment