My program is comprised of a bunch of threads happily chugging along, and the only synchronization I have is a volatile
global bool
that tells them if the user exited. All other communication between the threads is lockfree. These threads constantly have work to do, in a very time critical application, so I can't afford having locks between them. I recently came across a lot of information showing that volatile
is bad for multi-threading, so I want to make my code better. I saw that std::atomic_flag
is guaranteed lockfree, but I can't figure out how to use it for my case.
The basic setup is like this (omitting different files that the code is in):
// Global variable in its own .h file
extern volatile bool SystemOnline;
// Initialization in a .cpp file
volatile bool SystemOnline = true;
// Windows message processing
while (SystemOnline)
{
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
SystemOnline = false;
}
else if (!TranslateAccelerator(msg.hwnd, NULL, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
// Thread functions
void Thread1()
{
while (SystemOnline)
{
// Do some work
}
}
void Thread2()
{
while (SystemOnline)
{
// Do some other work
}
}
// And so on...
All threads are joined at the end.