Is the following comparison an atomic action? I.e., can it be reduced to a single CPU instruction?
char flag = 2;
for(;;)
{
if (!flag) // <-- this
break;
// sleep
}
Here’s what I’m doing:
int main()
{
sf::Mutex Mutex;
char flag = 2;
coordinatorFunction(flag);
for(;;)
{
if (!flag)
break;
// sleep
}
}
void workerFunction(void* a)
{
char* p = static_cast<char*>(a);
// work
GlobalMutex.Lock();
--*p;
GlobalMutex.Unlock();
}
void coordinatorFunction(char& refFlag)
{
sf::Thread worker1(&workerFunction, &refFlag);
sf::Thread worker2(&workerFunction, &refFlag);
worker1.Launch();
worker2.Launch();
}
This is the wrong way to go about it.
Your main thread is burning up CPU cycles as fast as it can, doing nothing but waiting for
flagto reach zero. This test will fail every time it’s attempted, except the last one. Instead of doing it in this manner, use the “join” facility that your thread objects most likely have to make the main thread suspend itself until all the workers complete.This way, not coincidentally, you won’t care if the test is atomic because you will not need it at all.