Since I've started multi-threading, I've been asking myself this one question :
Is writing and reading a variable from different threads undefined behavior?
Let's use the minimal example where we increment an integer in a thread and read the integer inside another one.
void thread1()
{
x++;
}
void thread2()
{
if (x == 5)
{
//doSomething
}
}
I understand that the addition operation is not atomic and therefore I could make a read from the second thread while the first thread is in the middle of the adding operation, but there is something i'm not quite sure of.
Does x
keeps his value until the whole addition operation is completed and then is assigned this new value, or does x
have an intermediate state where reading from it would result in undefined behavior.
If the first theory applies, then reading from x
while it's being writing to would simply return the value before the addition and wouldn't be so problematic.
If the second theory is true, could someone explain more in detail what is the process of the addition operation and why it would be undefined behavior (maybe with an example?)
Thanks