You are not logged in.

Dear visitor, welcome to QtForum.org. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

1

Wednesday, July 27th 2011, 7:13pm

Wait For All Threads to Be Finished

Heyho,
I'm currently working on a very small GUI program. There is one window and a few http and ftp connections are handled in the background.
When the mainwindow is closed the program will quit and I suspect it not to wait for all it's threads to finish (since I'm using QCoreApplication::exit(0) in my mainwindow's destructor).
Classes using e.g. an ftp connection close them by calling QFtp::close() on destruction. Same goes for a class using QNetworkReply and calling QNetworkReply::deleteLater() upon destruction.

Is there a way to wait in my mainwindow's destructor till all threads are done?
I found a way to wait/join (for) specific threads but non of them are manually created by me.

2

Thursday, July 28th 2011, 4:38am

could you add a loop in your threads where it checks if it is shutting down instead. something like:

Source code

1
2
3
4
5
6
7
8
9
10
11
void myThreadFunction()
{
    while ( !nowShuttingDown )
    {
        //handle your ftp upload or so 
        .....

        sleep(1);
    }
     QFtp::close()
}

and then when you want to quit, instead of calling QCoreApplication::exit(0) in your main thread right away

do a:

Source code

1
2
3
nowShuttingDown = true;
sleep(2);
QCoreApplication::exit(0);


?

3

Thursday, July 28th 2011, 1:13pm

But I can't access the threads used by classes like QFtp/QNetworkReply (without subclassing).

Junior

Professional

  • "Junior" is male

Posts: 1,613

Location: San Antonio, TX USA

Occupation: Senior Secure Systems Engineer

  • Send private message

4

Thursday, July 28th 2011, 3:11pm

Fake,

The QThread class provides several signals that help provide the status of the thread; started() and finished(). You could monitor the status of your thread by connecting these signals to a local slot that would maintain some sort of variable in tracking the status that could be used to trap in the closeEvent() of your mainwindow.

psuedo:

bool ftpActive;

connect( ftpThread, SIGNAL( started() ), mainwindow, SLOT( ftpStarted() ));
connect( ftpThread, SIGNAL( finished() ), mainwindow, SLOT (ftpFinished() ));

void MainWindow::ftpStarted(){ ftpActive = true; }
void MainWindow::ftpFinished(){ ftpActive = false; }

In the closeEvent you could trap for the ftpActive flag;
void MainWindow::closeEvent()
{
while( ftpActive ){ // do something: sleep or maybe show progress dialog in pulsate state while waiting for process to finish // };
}

Just a thought...

Similar threads