我如何在Qt中等待线程完成而不阻塞其执行
How do I wait for a thread to finish in Qt without blocking its execution?
我有一个函数,它创建了一堆qthread来加速长时间的计算,但是当我尝试睡觉直到计算完成时,后台线程由于某种原因从未执行。
我不明白为什么线程不执行后,我调用thread->start()
。下面是我的代码:
multithread.run_multithread(run_function, thread_count);
while(multithread.running)
QThread::msleep(100);
qDebug() << "done"; // Never reaches this point
和多线程功能:
void Multithread::run_multithread(std::function<void
(int)>run_function_in, int thread_count) {
running = true;
// Create workers and threads
int thread_idx;
for(thread_idx=0; thread_idx<thread_count; thread_idx++) {
ThreadWorker *worker = new ThreadWorker(this, run_function_in);
QThread *thread = new QThread();
// Set workers and threads to delete when done
worker->moveToThread(thread);
connect(worker, &ThreadWorker::finished, this, &Multithread::check_progress);
connect(thread, &QThread::started, worker, &ThreadWorker::run);
connect(worker, &ThreadWorker::finished, thread, &QThread::quit);
connect(worker, &ThreadWorker::finished, worker, &ThreadWorker::deleteLater);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
// Start thread
thread->start();
}
}
在Multithread::check_progress
中,当所有线程完成各自的计算后, running
被设置为false
。当我删除QThread::msleep(100)
计算将正常执行,但我需要一些方法阻塞,直到它完成。
与其使用QThread,我建议使用Qt Concurrent功能,它提供了线程原语之上更高层次的抽象。你可以使用QFutureSynchronizer
来等待几个并发的期货完成。此对象将等待所有附加的future完成后才允许自己被销毁。
如何启动多个线程,然后等待它们全部完成的示例如下:
#include <QtConcurrent>
void run_multithread(...) {
// Set up a new synchronizer.
QFutureSynchronizer<void> synchronizer;
// Run n tasks in parallel.
for (int thread_idx = 0; thread_idx < thread_count; ++thread_idx) {
synchronizer.addFuture(QtConcurrent::run(run_function_in));
}
// The synchroniser will wait for all threads to finish before returning.
}
这可能是因为优化,因为multithread.running
没有在循环内更改。然而,这里主要的可重复的原因是插槽Multithread::check_progress
从未被ThreadWorker::finished
信号调用,因为Multithread
的实例属于当前线程,但是事件循环被阻塞了。
当所有线程完成时,你可以从Multithread
对象发出一个信号,而不是这样的睡眠。然后可以从连接到该信号的插槽继续计算。
相关文章:
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 如何创建线程序列以按照启动顺序执行任务?
- 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?
- C++线程:如何在一个线程仍在运行时阻止另一个线程执行 (Win32)
- 如何制作一个只能在一个线程上同时执行的函数?
- 为什么即使调用了析构函数,C++11 中的分离线程也可以执行
- 工作线程在执行太快后永久休眠
- 超时后,线程睡眠不会继续执行
- 如何将带有参数的方法传递给线程以执行?
- 将执行循环拆分为多个线程 (1-N-1-N-1..)
- Visual Studio 发布模式阻止在调试模式下执行的代码.使用 WinHTTP 和多线程
- MFC执行线程问题
- Qt不能多次执行线程
- future::wait() 是否与 async() 执行线程的完成同步?
- std::线程何时执行线程
- 使用for循环执行线程
- 松弛的内存顺序效果是否可以扩展到执行线程的生命周期之后?
- 在C++11中,"不代表执行线程"的线程有什么意义?
- C++ 线程执行时间和另一个线程中的执行线程