Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean stop signal between threads

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?

like image 237
CaptainCodeman Avatar asked Dec 22 '22 17:12

CaptainCodeman


1 Answers

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.

like image 151
463035818_is_not_a_number Avatar answered Jan 09 '23 03:01

463035818_is_not_a_number