What is the simplest way to signal a background thread to stop executing?
I have used something like:
volatile bool Global_Stop = false;
void do_stuff() {
while (!Global_Stop) {
//...
}
}
Is there anything wrong with this? I know for complex cases you might need "atomic" or mutexes, but for just boolean signaling this should work, right?
std::atomic
is not for "complex cases". It is for when you need to access something from multiple threads. There are some myths about volatile
, I cannot recall them, because all I remember is that volatile
does not help when you need to access something from different threads. You need a std::atomic<bool>
. Whether on your actual hardware accessing a bool
is atomic does not really matter, because as far as C++ is concerned it is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With