2021年4月6日星期二

does volatile force the increment refresh the memory if the variable is updated

volatile int x;    # thread 1  x = 10;  # 1  x += 1;  # 2a, 2b    # thread 2  x = 20   # 3  

In the example code, 2 might be interleaved to a read operation 2a and an update operation 2b. In the case 1 - 2a - 3 - 2b, 2a first gets the value of x, which is 10, from the shared memory. Then 3 assigns 20 to x and writes into the shared memory immediately. For the next step 2b, will the thread memory that stores the variable x be forced to refresh due to the volatile keyword, which means the memory is updated to 20 and the result is 21? Or it still uses the previous value 10 and the result is 11?

Many thanks in advance!

https://stackoverflow.com/questions/66978642/does-volatile-force-the-increment-refresh-the-memory-if-the-variable-is-updated April 07, 2021 at 10:05AM

没有评论:

发表评论