如何正确使用带有while循环的线程
C++ How to correctly use threads with a while loop
我是新的线程,但我一直在阅读它在过去的几天,我现在正试图在一个实际的例子中实现它。
我有一个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()
来停止/加入/重置任务。
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 在 while 循环中使用 pow() 函数 C++
- C++ 制作/命名不初始化的向量(在 while 循环中)
- std::getline没有在while循环中重新请求用户输入