Making the main thread wait till all other Qthread

2019-02-22 12:02发布

is there a way to force the main thread to wait until all threads created from it, will finish their job, before finishing the program. I mean:

int main(){
    QthreadClass a; // in cons' a thread is created and running
    QthreadClass b; // same as before

    *** wish to wait till both created thread finished their jobs ***

    return 0;

}

标签: c++ qthread
2条回答
在下西门庆
2楼-- · 2019-02-22 12:11

Normally, with Qt you will have a QApplication based class with an event loop with signals and slots, that will not exit from the main function until you want to. In that case you can simply connect the QThread::finish() signal to a slot that checks if all threads are done.

Without an event loop and signals/slots, Qt threads don't have a join() method, found in other threading implementation, but QThread::wait() is somewhat similar.

bool QThread::wait(unsigned long time = ULONG_MAX)

Blocks the thread until either of these conditions is met:

  • The thread associated with this QThread object has finished execution (i.e. when it returns from QThread::run()). This function will return true if the thread has finished. It also returns true if the thread has not been started yet.
  • time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the thread must return from QThread::run()). This function will return false if the wait timed out.
查看更多
Explosion°爆炸
3楼-- · 2019-02-22 12:26

Well, what about:

a.wait();
b.wait();

Or, you would rather start an event loop (as usually for Qt applications) that you quit when both of your threads end (QThread emits finished() and terminated() signals).

查看更多
登录 后发表回答