如何停止运行永久阻塞循环的QThread? [英] How to Stop a QThread That Runs a Blocking Forever Loop?
问题描述
我已经尝试了一些粗糙的代码:
I have some rough code that I've been experimenting with:
someserver.cpp(GUI)
someserver.cpp (a GUI)
#include "server.h"
#include "ui_server.h"
Server::Server(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Server)
{
ui->setupUi(this);
}
Server::~Server()
{
delete ui;
}
void Server::onBtnStartClicked()
{
QThread worker;
worker.start(); // Start worker thread that goes into an infinite loop with a blocking call
}
void Server::onBtnExitClicked()
{
// How do I cleanly stop worker from running?
QApplication::quit();
}
worker.cpp
worker.cpp
#include "worker.h"
Worker::Worker(QObject *parent) :
QThread(parent)
{
}
void Worker::run()
{
for (;;)
{
// a blocking IO call here like pipe, or msgrcv
// process data received
}
}
由于工作线程以阻塞的IO调用在永久循环中运行,我将如何构造它,以便在GUI线程中按下停止"按钮时,工作线程会干净地停止?
Since the worker thread runs in a forever loop with a blocking IO call, how will I be able to structure this so that when the Stop button is pressed in the GUI thread, the worker thread is stopped cleanly?
推荐答案
您当然可以在每次迭代检查的Worker::run()
中的for循环中放入一个布尔值,该值在== true处中断,由gui Stop设置.按钮.当然,这在执行被阻止时不会退出线程.
You could of course put a boolean value within the for loop in Worker::run()
checked every iteration, which breaks on ==true and is set by the gui Stop button. Of course, this won't quit the thread while execution is blocked.
可能更好的方法是摆脱for
循环,并使用Qt的信号和插槽来设置回调函数,该回调函数连接到类似于QIODevice::readyRead()
的信号.仅当套接字/管道中有可用信息时,才调用它们.在任何其他时间,您都可以使用QThread::exit()
退出线程.您还需要在某个时刻调用QThread::exec()
,以使事件循环继续进行.
Probably better is to get rid of the for
loop and use Qt's signals and slots to setup a callback function, connected to a signal like QIODevice::readyRead()
. These will be called only when there is information available in the socket/pipe whatever. Any other time you'll be able to quit the thread with QThread::exit()
. You'll need to call QThread::exec()
at some point as well to get the event loop going.
这篇关于如何停止运行永久阻塞循环的QThread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!