Increase and decrease integer at the same time

I had this question for a while - is it possbile (not intended, but if this "error" can occur) to actually increase AND decrease integer with ANY operation at the same time, so the result will be screwed integer? like this

1
2
3
4
5
int a = 0;
//some code
a++;
//meanwhile at the very same time, not the same code, so another thread or something
a -= 5


if it would go normally, the a would == -4, however is there any way that it will screw itself, and the "a" will be -5, or 1, or just will be somehow broken?
Last edited on
Multiple threads accessing the same memory at the same time results in a race condition. Race conditions result in undefined behavior. Literally anything can happen. a might remain unchanged... or it might have 4 subtracted... or it might be filled with random garbage... or your program might crash.


To prevent this, memory shared between threads needs to be guarded. Typically this is done either with a mutex (see the <mutex> header), or by making the variable atomic (see the <atomic> header).
Yes, C++ doesn't stop you from shooting yourself in the foot.

you can do it in the same expression: std::cout << (a -=5) << (a++);, but the behavior of the program that attempts to evaluate such expression is undefined

Likewise with threads - if one thread executes a++; and another a-=5;, without synchronization or without changing the type of a to std::atomic<int>, the behavior of the program is undefined.
...the answers given mean that you can try, but the results are "undefined" -- meaning, as was said, that anything can happen.

Think about it. Can a number be both 3 and 5 at the same time?

No. Of course not. A 3 is a 3 and a 5 is a 5. A 3 cannot be a 5, nor can a 5 be a 3.

It is like dividing by zero. Mathematically, the answer is anything you want it to be. Hence, most people will just tell you that you can't do that.

An atomic value can only be one thing at a time.

Hope this helps, unless I misunderstood your question...
Topic archived. No new replies allowed.