QtConcurrent::run如何停止后台任务
QtConcurrent::run how to stop background task
我也有这样的情况:stop thread started by qtconcurrent::run
我需要在 QMainWindow 的 closeEvent 上关闭子线程(以 QtConcurrent::run 开始)。
但是我在子线程中的函数使用 *.dll 中的代码:我不能使用循环,因为我所做的一切 - 正在调用 external dll like
QFuture<void> = QtConcurrent::run(obj->useDllfunc_with_longTermJob());
当我使用 x 按钮关闭应用程序时,我的 gui 已关闭,但第二个线程 with_longTermJob() 仍然有效,当完成时出现错误。
我知道一些决定:
- 使用其他函数,如 map() 或其他与
QFuture.cancel/stop 功能,而不是 QtConcurrent::run()。但我只需要一个函数调用。 运行() 是我需要的。
- 或者改用 QThread Concurrent.But 这对我不好。
哪种方法更简单更好,我该如何实现?有没有我没有列出的方法?
您能否提供小代码示例以供决策。谢谢!
QtConcurrent::run
在这里不是问题。你必须有办法停止 dllFuncWithLongTermJob
。如果你没有这样的手段,那你用的API就坏了,你倒霉了。您无能为力通常是安全的。强行终止线程会使堆处于不一致状态等。-如果需要终止线程,则需要立即中止应用程序。
希望你可以调用类似 stopLongTermJob
的东西来设置一些标志来中断 dllFuncWithLongTermJob
。
然后:
auto obj = new Worker;
auto objFuture = QtConcurrent::run([=]{obj->dllFuncWithLongTermJob();});
打断:
obj->stopLongTermJob(); // must be thread-safe, sets a flag
objFuture.waitForFinished();
我也有这样的情况:stop thread started by qtconcurrent::run
我需要在 QMainWindow 的 closeEvent 上关闭子线程(以 QtConcurrent::run 开始)。 但是我在子线程中的函数使用 *.dll 中的代码:我不能使用循环,因为我所做的一切 - 正在调用 external dll like
QFuture<void> = QtConcurrent::run(obj->useDllfunc_with_longTermJob());
当我使用 x 按钮关闭应用程序时,我的 gui 已关闭,但第二个线程 with_longTermJob() 仍然有效,当完成时出现错误。 我知道一些决定:
- 使用其他函数,如 map() 或其他与 QFuture.cancel/stop 功能,而不是 QtConcurrent::run()。但我只需要一个函数调用。 运行() 是我需要的。
- 或者改用 QThread Concurrent.But 这对我不好。
哪种方法更简单更好,我该如何实现?有没有我没有列出的方法? 您能否提供小代码示例以供决策。谢谢!
QtConcurrent::run
在这里不是问题。你必须有办法停止 dllFuncWithLongTermJob
。如果你没有这样的手段,那你用的API就坏了,你倒霉了。您无能为力通常是安全的。强行终止线程会使堆处于不一致状态等。-如果需要终止线程,则需要立即中止应用程序。
希望你可以调用类似 stopLongTermJob
的东西来设置一些标志来中断 dllFuncWithLongTermJob
。
然后:
auto obj = new Worker;
auto objFuture = QtConcurrent::run([=]{obj->dllFuncWithLongTermJob();});
打断:
obj->stopLongTermJob(); // must be thread-safe, sets a flag
objFuture.waitForFinished();