QThreadPool 强制停止在 qt cpp 中
QThreadPool force stop in qt cpp
我已经创建了Qthreadpool。 我想从队列中删除所有任务。代码如下。
void MainWindow::startThread()
{
thread= new QThradPool(this);
thread->setMaxThreadcount(1);
hello = new HelloWordTask();
thread->start(hello);
}
void MainWindow::stopThread()
{
thread->clear();
delete thread;
delete hello;
// but current task is not stopping. until it is finished. i want to stop it
immediately .
}
void HelloWordTask::run()
{
// function which takes time
}
这通常是不可能的。有些QFuture
- 不是QtConcurrent::run
返回的那些 - 是可以取消的。如果您使用的是 QtConcurrent::run
或提交通用QRunnable
,则需要使其可取消。这个答案提供了一种生成在线程池上运行的可取消未来的方法。然后,您需要跟踪这些期货并取消任何正在进行的期货。
一般来说,不需要动态创建线程池 - 只需按值存储它。一旦你使用了QFuture
接口,也不需要管理任务的生存期:期货是这个对象的句柄,一旦最后一个对象消失,任务对象就会被释放。
class HelloWorldTask : RunControllableTask<void> {
// see https://stackoverflow.com/a/16729619/1329652
...
};
class MainWindow : public QMainWindow {
QThreadPool m_pool;
QVector<QFuture<void>> m_futures;
public:
explicit MainWindow(QWidget * parent = {}) : QMainWindow(parent) {
m_pool.setMaxThreadCount(1);
}
void startTask() {
auto future = TaskExecutor::run(new HelloWorldTask());
m_futures.push_back(future);
}
void stopAllTasks() {
m_pool.cancel();
for (auto &future : m_futures)
future.cancel();
while (!m_futures.isEmpty())
m_futures.takeLast().waitForFinished(); // this will free the task too!
Q_ASSERT(!m_pool.activeThreadCount());
}
~MainWindow() override {
stopAllTasks();
}
};
您也可以使用 future 接口从任务中线程安全地返回数据!
相关文章:
- 如何在cpp文件之间切换窗口?在Qt中
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 在Qt-cpp中通过像素获取QString的子字符串
- QT - 连接 Qml 按钮 单击到 Cpp 构造函数
- 尝试使用 CPP 在一个 Qt 窗口中显示多个 png 文件
- 如何在Qt cpp的SQlite数据库中插入变量的值
- QT 如何包含标头和 cpp 文件
- 如何从QT中的另一个CPP文件中访问CPP文件中的变量
- Qt cpp - 将QString写入文本文件的干净方法
- QThreadPool 强制停止在 qt cpp 中
- Qt按住鼠标按钮和计时器CPP
- QT - 现有插槽在主寡妇.cpp中不可见
- 如何使用QT或Linux上的任何其他CPP框架播放WMA音频文件
- 找不到 CPP 中来自外部源的函数 (Qt)
- 找不到构造函数 - 如何将 CPP 文件添加到 Qt 构建过程
- 如何从 QT 中的.cpp访问 QML 中的一个复选框
- 从QT创建者中的.QML文件生成.cpp和.h文件
- 如何运行需要QT的简单CPP文件
- QT CPP延迟循环
- 如何在QT创建项目中使用RESTCLIENT-CPP