c++ - Qt C++ 如果 moveToThread 如何停止线程

标签 c++ qt qthread quit

经过大量实验并从 stackoverflow 学习之后,我创建了一个 QObject worker、一个 QThread,并将我的 QObject worker 移动到我的 QThread,并启动了 QThread - 它正在运行!

void TelnetServer::incomingConnection(qintptr socketDescriptor)
{
    QThread * TelnetConnectionThread = new QThread(this);
    TelnetConnection *worker = new TelnetConnection(socketDescriptor,TelnetConnectionThread);
    connect(TelnetConnectionThread, SIGNAL(started()), worker, SLOT(start()));
    connect(TelnetConnectionThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
    worker->moveToThread(TelnetConnectionThread);
    TelnetConnectionThread->start();  // Start the thread running
}

我假设调用 TelnetConnectionThread->start() 会在 QThread 中启动事件循环(因为它似乎正在运行)。现在的问题是……如何停止线程?我试过:

QThread::quit();

但是当我关闭应用程序时线程仍在运行。这是否意味着 exec 循环没有运行?我是否需要做其他事情来停止这个线程?还是实际上已停止但未删除?

最佳答案

从设计和技术角度来看,终止正在运行的线程是个坏主意。 通常线程必须拥有基于“终止”标志的退出决定。例如,创建新标志“stop”,如果 quit() 插槽发出信号,则将标志标记为 true。在线程函数中定期验证标志,如果为真 - 退出线程函数。

关于c++ - Qt C++ 如果 moveToThread 如何停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299186/

相关文章:

javascript - 如何使用 QJSEngine 构建 API?

qt - 播放声音文件的摘录

c++ - QThread::run() 中的 std::condition_variable 用法

c++ - QTimer 不调用超时槽

c++ - QThread,在线程上创建 GUI 小部件元素

c++ - 具有多个模板参数的模板特化

c++ - 修剪连续的标准容器

c++ - Qt DBus连接不适用于SLOT参数中的typedef

c++ - 从另一个类调用指向成员函数的指针

c++ - 确认在类构造函数中从文本文件初始化变量