Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of volatile keyword

Tags:

c#

volatile

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

like image 740
Sri Harsha Velicheti Avatar asked Jan 23 '26 12:01

Sri Harsha Velicheti


1 Answers

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.

like image 116
Servy Avatar answered Jan 25 '26 02:01

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!