Prepare for your Next Interview
|
Welcome to the Geeks Talk forums. You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today! If you have any problems with the registration process or your account login, please contact contact us. |
This is a discussion on Static variables in multiuser environment within the C and C++ forums, part of the Software Development category; 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 ...
|
|||||||
|
|||
|
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) |
| Sponsored Links |
|
|||
|
Re: Static variables in multiuser environment
Quote:
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. |
![]() |
|
| Thread Tools | |
| Display Modes | |
|
|