首页 > 解决方案 > 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?

标签: c++multithreadingc++11

解决方案


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.


推荐阅读