Reputation: 497
I am reading about volatile keyword and wondering how would the below scenario workout.
Class SomeClass
{
volatile int i = 10;
}
Two threads are trying to modify the variable i.
Thread 1 does i = i + 1;
Thread 2 does i = i - 1;
The sequence of operations is as follows:
Thread 1 reads variable i to CPU register. Thread switch happens at this point. Thread 2 reads variable i and decrements it by 1 so now value of i is 9; Thread 1 is scheduled again, now will the thread 1 take the i value form register (which is 10) and increment it to 11 and write it back to i or will it read from the original source and read the i value as 9 and increment it to 10?
Thanks
Upvotes: 3
Views: 107
Reputation: 1474
As you wrote "Thread 1 is scheduled again, now will the thread 1 take the i value form register (which is 10) and increment it to 11 and write it back to i or will it read from the original source and read the i value as 9 and increment it to 10?" - EDIT: with help of @Servy: the 1-st thread will use value of 10 because it was previously read to perform next add operation.
Upvotes: 0
Reputation: 203802
The increment/decrement operations are not atomic, so the race condition that you have described is entirely possible. The use of volatile
doesn't prevent it. You would need to use a lock
, or possibly Interlocked.Increment
, instead, to ensure that the operations are each atomic.
Upvotes: 8