Have a structure declared and defined in shared file.
Both threads create by the Windows API CreateThread()
have visibility to the instance of it:
struct info
{
std::atomic<bool> inUse;
string name;
};
info userStruct; //this guy shared between two threads
Thread 1 continually locking/unlocking to write to member in structure (same value for test):
while (1)
{
userStruct.inUse = true;
userStruct.name= "TEST";
userStruct.inUse = false;
}
Thread 2 just reading and printing, only if it happens to catch it unlocked
while (1)
{
while (! userStruct.inUse.load() )
{
printf("** %d, %s\n\n", userStruct.inUse.load(), userStruct.name.c_str());
Sleep(500); //slower reading
}
printf("In Use!\n");
}
Expect to see a lot of:
"In Use!"
and every once if it gets in, when unlocked:
"0, TEST"
..and it does.
But also seeing:
"1, TEST"
If the atomic bool is 1 I do NOT expect to ever see that.
What am I doing wrong?