终止工作线程的正确方法

时间:2017-08-16 23:50:18

标签: c++ multithreading

您好我正试图找出终止工作线程的最佳和平方式。我有以下代码:

class test{
  public:
test() {}
~test() {}

std::atomic<bool> worker_done;


int a;
void pr() {
    while (true) {
        if (worker_done) {
            break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        printf("%d \n", a++);
    }
}

std::thread* m_acqThread;
void continuous() {
    m_acqThread = new std::thread(&test::pr, this);
}

void stopThread(){
    if (m_acqThread) {
        if (m_acqThread->joinable())
            m_acqThread->join();
        delete m_acqThread;
        m_acqThread = nullptr;
    }
}


};


int main(){

test t;
t.continuous();

std::this_thread::sleep_for(std::chrono::milliseconds(2000));
t.worker_done = true;

t.stopThread();


std::string str;
std::cin.clear();
getline(std::cin, str);
return 0;

除了将“worker_done”设置为true之外,是否有更好的方法通知工作人员的线程被终止?

由于

1 个答案:

答案 0 :(得分:2)

你有什么不错:如果你有一个atomic<bool>说你的程序打开时开始,并且当你的程序关闭时你需要停止它,使用#include <thread> #include <atomic> #include <iostream> std::atomic_flag lock; int n = 0; void t() { while (lock.test_and_set()) { ++n; std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } int main() { lock.test_and_set(); std::thread t(&t); std::this_thread::sleep_for(std::chrono::seconds(2)); lock.clear(); t.join(); std::cout << n << std::endl; std::cin.get(); } 是正确的方法此

也可以这样使用std::atomic_flag

atomic<bool>

你可以阅读why you might wish to choose atomic_flag over atomic<bool>,但我个人更喜欢使用std::atomic<bool> runThread; int n = 0; void t() { while (runThread) { ++n; std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } int main() { runThread = true; std::thread t(&t); std::this_thread::sleep_for(std::chrono::seconds(2)); runThread = false; t.join(); std::cout << n << std::endl; std::cin.get(); } 这样的事情,因为它更具可读性:

    <progControls:CalibrationSummary

    </progControls:CalibrationSummary>

    <!--<TextBlock Text="{Binding Path=NumberOfCalibrations, Mode=OneWay}"/>-->