int i=5;
f()
{
i++;
i--;
}
For the above code if three threads execute the above function f() simultanously then what can be the total different values of global variable i are possible?
Note : i is initialized to 5 globaly.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I would say that’s an exercise in combinatorics, which I’m personally not going to do, however I do want to make clear that this is NOT the correct way to have threads execute this
f(). The problem is that the implementation ofoperator++is not a single instruction, which means that halfway through one call tooperator++it could context switch and do anotherf()in another thread. This would then lead to corrupt state of your variablei.So determining the possible values of
iwithout proper synchronization is useless, since it could be any number of values, real or unreal, as things might go corrupt.