If I have a global counter and I have two threads that are each incrementing it 100 times in a loop, why is it possible that I can have a value other than 200? I don’t see how accessing the variable is nonatomic.
Share
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.
That is because for most environments, incrementing a memory location is not an atomic operation.
The sequence of events would be something like
To ensure a consistent result, you must make the increment operation atomic. This is often done by placing a thread lock around the increment operation. For example, in C# that might look like
Alternatively, in the .NET environment, one could use Interlocked.Increment
http://msdn.microsoft.com/en-us/library/dd78zt0c.aspx
Other environments have similar constructs.
The best reference I have ever come across for threading in the .NET environment (but is a useful read no matter what your environment) is the following
http://www.albahari.com/threading/