gpt4 book ai didi

c++ - 如何在 Qt 中等待线程完成而不阻塞其执行?

转载 作者:行者123 更新时间:2023-11-28 06:00:35 32 4
gpt4 key购买 nike

我有一个函数可以创建一堆 QThreads 来加速长时间的计算,但是当我尝试休眠直到计算完成时,后台线程由于某种原因永远不会执行。

我无法弄清楚为什么在我调用 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();
}
}

runningMultithread::check_progress 中被设置为 false 当所有线程完成他们的部分计算时。当我删除 QThread::msleep(100) 时,计算将正常执行,但我需要一些方法来阻止直到它完成。

最佳答案

我建议使用 Qt Concurrent 功能,而不是使用 QThread,它提供了比线程原语更高级别的抽象。您可以使用 QFutureSynchronizer 等待多个并发 future 完成。该对象将等待所有附加的 futures 完成,然后才允许自身被销毁。

如何启动多个线程然后等待它们全部完成的示例是:

#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.
}

关于c++ - 如何在 Qt 中等待线程完成而不阻塞其执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357764/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com