As it was noticed before, this trick could be performed with volatile
. This is more honest approach compared to operator changing. Just let us use two threads:
volatile int a;void changingValue(){ std::srand(unsigned(std::time(0))); while (true) { a = (rand() % 3 + 1); }}void checkingValue(){ while (true) { if (a == 1 && a == 2 && a == 3) { std::cout << "Good choice!"<< std::endl; } }}int main() { std::thread changeValue = std::thread(changingValue); changeValue.detach(); std::thread checkValue = std::thread(checkingValue); checkValue.detach(); while (true){ continue; }}
Moreover, this code in my case is working well with no volatile
declaration. As far as I understand, it should depend on compiler and processor. Maybe someone could correct it, if I'm wrong.