Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;如何正确使用带有while循环的线程_C++_Multithreading - Fatal编程技术网

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

C++ C++;如何正确使用带有while循环的线程,c++,multithreading,C++,Multithreading,我是线程新手,但在过去的几天里我一直在阅读它,现在我正试图在一个实际的例子中实现它 我有一个GUI类,点击一个按钮就会启动一个线程。我的执行情况如下: void Interface::on_startButton_clicked() { theDetector.start(); } void Interface::on_stopButton_clicked() { //not sure how to stop the thread } 探测器类则具有以下

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

我有一个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冻结后立即加入它,就像怀疑的那样。
执行此示例的正确方法是什么?

检测器应具有
std::unique\u ptr pThread和a
std::原子暂停

如果存在
pThread
,则
Start
不应执行任何操作。否则,
halt=false;重置(新的std::thread(&Detector::Task,this))

不要分离——这很少是个好主意

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

Detector::Task
中,在(!halt)
时循环

如果任务
中的代码更复杂,单个循环可能太长,无法等待UI响应,则您需要延迟加入
,直到使用不同的方法


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

您不能通过布尔值停止任务是什么意思?您只是不能分离线程,然后再尝试加入它们。@chris他可能发现编译器优化了加载。。。我给它10分钟,直到有人建议volatile(这不是解决方案)好吧,如果它是由另一个线程设置的,那么它应该是一个
atomic\u bool
,这样你就不会进行并发读写。@chris是的,我在使用普通bool时得到了“无效的parameter传递到运行时”,我的错。因此,如果我使用atomic_bool并保持其余部分不变,这是一种高效且智能的方法来完成这个示例吗?我不确定拆下它是否如此聪明。。。就像我说的,我还是个新手。谢谢!我很难理解你所说的“如果有pThread,Start应该什么都不做”是什么意思。你想让我检查线程是否正在运行,对吗?我该怎么办this@isADon,如果它正在运行,这意味着
pThread
有一个值(因为您在启动线程时设置了
pThread
),因此
If(pThread)
将执行下一条语句。