[SOLVED] How to wait for all threads in main thread?



  • I just post the most interesting places from my application, could you please help me and describe how I should wait for all threads?

    main.c:
    @int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    bdConnection = new RmSqlConnection();
    
    GetMail* getMail = new GetMail(bdConnection);
    getMail->startThreads();
    
    return a.exec();
    

    }
    @

    getthread.c
    @QThread* GetMail::addThread(int userId)
    {
    GetMailTask* getTask = new GetMailTask(sysRootPath, archPath);
    QThread* thread = new QThread;

    getTask->moveToThread(thread);
    
    connect(thread,  SIGNAL(started()),  getTask, SLOT(process()));
    connect(getTask, SIGNAL(finished()), thread,  SLOT(quit()));
    connect(this,    SIGNAL(stopAll()),  getTask, SLOT(stop()));
    connect(getTask, SIGNAL(finished()), getTask, SLOT(deleteLater()));
    connect(thread,  SIGNAL(finished()), thread,  SLOT(deleteLater()));
    connect(getTask, SIGNAL(finished()), this, SLOT(startNewThread()));
    
    return thread;
    

    }

    void GetMail::startThreads() {

    int i = 1;
    QThread* thread;
    
    /* Prepare threads */
    while(userEntry_r.next()) {
    
        if (NULL != (thread = addThread(userId))) {
            threadList.append(thread);
        }
    }
    
    /* Run threads */
    while ( (!threadList.isEmpty()) && (i <= maxNumberOfThreads) ) {
        threadList.takeFirst()->start();
        i++;
    }
    

    }

    void GetMail::startNewThread() {

    if (threadList.isEmpty()) {
        return;
    }
    
    threadList.takeFirst()->start();
    

    }
    @

    getmailtask.c:
    @
    void GetMailTask::process()
    {
    ...Do something...
    emit finished();
    }@



  • So, may be the following change may give some positive effect?

    @void GetMail::startNewThread() {

    if (threadList.isEmpty()) {
    
        if (maxNumberOfThreads-- == 0) {
            /* All started thread are finished, lets close application */
            QApplication::exit(0);
        }
    
        return;
    }
    
    threadList.takeFirst()->start();
    

    }@



  • Hi unmanner, yes I was just about to suggest that you need a way of tracking your threads. You can either have a list to all the threads you start and delete them out of the list when you get the finished() signal.

    Or you can have a counter and wait for it to reach zero. But it looks like you are on the right track there...


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.