如何正确使用带有while循环的线程

C++ How to correctly use threads with a while loop

本文关键字:while 循环 线程 何正确      更新时间:2023-10-16

我是新的线程,但我一直在阅读它在过去的几天,我现在正试图在一个实际的例子中实现它。

我有一个GUI类,点击一个按钮应该启动一个线程。我的实现如下:

void Interface::on_startButton_clicked()
{    
    theDetector.start();    
}
void Interface::on_stopButton_clicked()
{    
    //not sure how to stop the thread
}

然后检测器类有以下代码:

void Detector::start()
{
    thread t1(&Detector::detectingThread, this);
    t1.detach();
}
void Detector::detectingThread()
{
    isActive = true;
    while (isActive){
       //run forever and do some code
       //until bool is set to false by pressing the stop button
    }
}

我觉得这样做不对。如果我分离线程,我不能通过布尔值停止它,如果我在GUI冻结后立即加入它。做这个例子的正确方法是什么?

TheDetector应该有一个std::unique_ptr<std::thread> pThread;和一个std::atomic<bool> halt;

如果存在pThread

Start不应该做任何事情。如果没有,halt=false; pThread.reset(new std::thread(&Detector::Task, this));

不要脱离——这不是一个好主意。

Stop中,先设置halt=true;,再设置if (pThread) { pThread->join(); pThread.reset(); }

Detector::Task中,循环while (!halt) .

如果Task中的代码更复杂,并且单个循环可能太长而无法等待UI响应,则需要将join推迟到另一个方法。

您还需要添加Detector::~Detector()来停止/加入/重置任务。