Created
August 23, 2020 16:41
-
-
Save arihantdaga/37acea6d02fc7de4f2419c0494678395 to your computer and use it in GitHub Desktop.
A simple demonstration of how race conditions can occur in nodeJs and also how to tackle that
This file contains 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
let _arr = []; | |
let count = 0; | |
class Lock { | |
constructor() { | |
this._locked = false; | |
this._waiting = []; | |
} | |
lock() { | |
var unlock = () => { | |
let nextResolve; | |
if (this._waiting.length) { | |
nextResolve = this._waiting.pop(0); | |
nextResolve(unlock); | |
} else { | |
this._locked = false; | |
} | |
} | |
if (this._locked) { | |
return new Promise((res, rej) => { | |
this._waiting.push(res); | |
}) | |
} else { | |
this._locked = true; | |
return new Promise((resolve) => { | |
resolve(unlock); | |
}); | |
} | |
} | |
} | |
let lock = new Lock(); | |
async function addToArray(item) { | |
count++; | |
let unlock = await lock.lock(); | |
_arr.push(item); | |
if (_arr.length == 1000000) { | |
await backupAndEmptyArray(); | |
} | |
await unlock(); | |
} | |
async function backupAndEmptyArray() { | |
const backup = []; | |
for (let i = 0; i < 1000000; i++) { | |
backup.push(_arr[i]); | |
} | |
await delay(1); | |
_arr = []; | |
} | |
async function delay(t) { | |
return new Promise((res, rej) => { | |
setTimeout(res, t); | |
}); | |
} | |
async function add10000000ElementsToArray(k) { | |
let i = 10000000; | |
while (i--) { | |
if (i % 5996 == 0) { | |
await delay(1); | |
} | |
await addToArray({ | |
key: "Value" | |
}); | |
} | |
} | |
async function main() { | |
let promise1 = add10000000ElementsToArray(1); | |
let promise2 = add10000000ElementsToArray(2); | |
let promise3 = add10000000ElementsToArray(3); | |
let promise4 = add10000000ElementsToArray(4); | |
await promise1; | |
await promise2; | |
await promise3; | |
await promise4; | |
console.log(count); | |
console.log(_arr.length); | |
} | |
main().then(() => { | |
console.log("DONE"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment