Consider the following piece of multiple - threaded code -
#include <iostream>
#include <thread>
using namespace std;
int a = 0;
bool alive = 1, start = 0;
void detector()
{
int local_a = 0;
while (alive)
{
if (start)
{
if (a != local_a)
{
cout << " change detected!\n";
local_a = a;
}
start = 0;
}
}
}
int main(int argc, char *argv[])
{
std::thread t(detector);
int count = 10;
while (count--)
{
a = rand();
start = 1;
cout << a << '\n';
while (start)
{
};
}
alive = 0;
t.join();
return 0;
}
My question is, is this architecture thread safe (except for consol logging part where printed text might get mixed but it is done our convenience, not the part of my working code so i only care about if my variables are having data-race)? I know i haven't used any mutex but anywhere where read and write occurs simultaneously between two threads, one thread is just waiting to see a particular value and one is writing. So no matter what the order of read-write of those threads are, one thread is always reading it again to detect a particular write (a single operation).
I have ran this on my machine and works correct but I don't know if it can show undefined behaviour on other machines so i just want to confirm.