Search code examples
c++stdatomic

Is it safe to write "y=++x" when using c++ atomic?


If I have 2 threads and in main function, I init a variable x like this

std::atomic<int> x=0;,

In thread 1 I do this:

while(true){
  x++;
}

And In thread 2 I do this:

y=++x;

my question is that:is there any possibility that variable y can get the wrong number?

I mean for example:

if in thread2,at that moment,x=2;then because of "++x",x=3,so I hope y=3;

But I am afraid that between "++x" and "y=x", thread 1 will rewrite x again, so I may have y=4 or something.


Solution

  • If the concern is that in y=++x value in x equals to 2 first, then increased to 3 by ++x, then increased by another thread again before copying to y, then answer is no - this can't happen. Result of operation ++x is not a reference to the atomic value itself - it is plain int result of post-increment and the operation guarantees that you will have exactly the value after increment returned (without additional read).