While learning multithread programming I've written the following code.
#include <thread>
#include <iostream>
#include <cassert>
void check() {
int a = 0;
int b = 0;
{
std::jthread t2([&](){
int i = 0;
while (a >= b) {
++i;
}
std::cout << "failed at iteration " << i << "\n"
// I know at this point a and b may have changed
<< a << " >= " << b << "\n";
std::exit(0);
});
std::jthread t1([&](){
while (true) {
++a;
++b;
}
});
}
}
int main() {
check();
}
Since ++a always happens before ++b a should be always greater or equal to b.
But experiment shows that sometimes b > a. Why? What causes it? And how can I enforce it?
Even when I replace int a = 0; with int a = 1000; which makes all of this even more crazy.
The program exits soon so no int overflow happens. I found no instructions reordering in assembly which might have caused this.