我有一個函數可以創建一堆QThreads來加速長時間計算,但是當我嘗試並休眠到計算完成時,後臺線程從不會因爲某種原因而執行。如何等待一個線程在Qt中完成而不會阻止它的執行?
我找不到爲什麼線程在我呼籲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();
}
}
running
被設置爲false
在Multithread::check_progress
當所有線程完成其計算的一部分。當我刪除QThread::msleep(100)
計算將正常執行,但我需要一些方法來阻止,直到它完成。
而是阻止,你可能會考慮讓每個線程火的信號,以表明其完成。然後你只需要一個插槽來計算它被調用的次數,以便知道計算完成的時間。 – MrEricSir
@MrEricSir如果可以的話,我會這樣做,但是我需要在一個函數內連續多次執行多線程計算,所以很難跟蹤每次多線程計算完成時的哪一點。此外,我覺得有一些明顯的概念,我沒有得到。我不明白爲什麼我的代碼無法正常工作。 – user1389840