Static variables in multiuser environment
If in a multiuser system a static variable is initialized as 10 and the first user increments its value by 1 and then the second user increments its value by one.
What is the value of the variable now?
(This question was asked in Accenture Technical Interview)
Re: Static variables in multiuser environment
Re: Static variables in multiuser environment
i aggred to the above answer
Re: Static variables in multiuser environment
[QUOTE=Lokesh M;716]If in a multiuser system a static variable is initialized as 10 and the first user increments its value by 1 and then the second user increments its value by one.
What is the value of the variable now?
(This question was asked in Accenture Technical Interview)[/QUOTE]
This question is a trap. Be careful how you answer this. The answer is that the value is non-deterministic due to the possibility of a race condition.
Details below.
- Lets take an example. Let us say that the static variable is x and its value is 10. Lets say that two processes/threads are doing the increment: let us name them as P1 and P2.
- a increment operation in C (or in any other programming language) is actually three operations at the machine level i.e. a load, modify and a store.
- So, since there is no locking implemented to access the static variable, the load, modify and store can be started by P1 and P2 at any time.
- For example, lets say P1 and P2 started the load instruction at the same time. Both will read a value of 10 from x, both will increment to 11 and both will write 11 back. So, in this case, an increment is lost.
- Another example, lets say that P1 started its load first, and read 10, incremented and then stored 11 back to memory. If P2 now starts the load, the value will be 12.
- Since the order/timing of the instructions determine the outcome, this is a perfect example of a race condition. This is why we need locking to protect access to global scope variables.
Hope that helps.