How can I add value to a variable at the same time? If I can what result will be? crash or something else?
For example:
int a;
so there will be 2 thread to adding value once.
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.
If you do this in an uncontrolled fashion, it’s quite possible that you’ll lose data.
Each thread will take three steps:
If they both perform the first step roughly together, the result will be an increment of 1 instead of 2.
Additionally, there are memory model issues where one thread may not “see” the write from another thread. Memory models are complex beasts…
Use
Interlocked.Incrementto perform an atomic increment, which also uses volatile memory access to make sure it always sees what other threads have written.Sample of broken code:
Running on my laptop just now, that showed a result of 1011788.
Change this line:
to this:
and it all works beautifully.