I'm using a Nodejs Api server and facing a special situation where a bunch of users notify me with a boolean indication, and only when all users sent me the indication, I'm then calling a method to do some job.
So for the example, I create a group of 5 connected users, and wait for their indications, which is sent using an Http Post message with an input boolean. so, on the server I hold an object as follows -
Group = {
actionPerformed: false,
userOne: false,
userTwo: false,
userThree: false,
userFour: false,
userFive: false
}
Upon receiveing a message from any of the following users, I update the relevant property, lets say, for userOne I set Group.userOne property to true. I then check if all other users have already send thier indication, so I perform the following test -
if (!Group.actionPerformed &&
Group.userOne &&
Group.userTwo &&
Group.userOne &&
Group.userThree &&
Group.userFour &&
Group.userFive) {
Group.actionPerformed = true;
//do something only once
}
Of course, I want to perform the above code in brackets only once therefore I want to avoid a race condition situation where the 2 last users send their indications on the exactly same time, and both will set their propery to true, and afterwards as checking the condition, the first user might check the condition - which will result with true, and before setting the actionPerformed to true, a thread switch might happen, and a second user will test the condition which will also result with true, then both user will enter the brackets.
So my question is, Is the described situation can only be solved with an atomic operation on the condition and Group.actionPerformed = true or, is there another solution, maybe more elegant ?
UPDATE - the above code is performed within a route async method -
router.route('/')
.get(passport.authenticate('jwt', { session: false }), async (req, res, next) => {
....
if (!Group.actionPerformed &&
Group.userOne &&
Group.userTwo &&
Group.userOne &&
Group.userThree &&
Group.userFour &&
Group.userFive) {
Group.actionPerformed = true;
//do something only once
}
});