PDA

View Full Version : problem running GUI thread and worker thread concurrently



prkhr4u
17th October 2013, 09:31
I am using 2 threads: GUI thread and 1 worker thread(grabthread),but i am not able to run them concurrently.
My main() function is like this :

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow win;
win.show();
GrabThread thread;
thread.start();
qDebug() << "hello from GUI thread " << a.thread()->currentThreadId();
thread.wait(); // do not exit before the thread is completed!
return a.exec();
}

and grabthread.h like this:

class GrabThread : public QThread
{
Q_OBJECT
private:
void run();
};

What is happening is that My GUI pops up only after grabthread has been fully executed and exits.
I want my GUI and grabthread to start simultaneously so that i can use multithreading.

^NyAw^
17th October 2013, 09:56
Hi,



...
thread.start();
thread.wait();
...
return a.exec();


This code waits until the thread finishes to start the main application.

pkj
17th October 2013, 10:07
What is happening is that My GUI pops up only after grabthread has been fully executed and exits.
I want my GUI and grabthread to start simultaneously so that i can use multithreading.

In the QThread::run() function have you written exec() ? Untill you do that the event loop of your thread will not start. The default implementation of QThread run just has the exec.

Also note that that for almost all the cases, QThread need not be inherited from thread. Refer the latest notification. This will make you life easy with one less inherited class to worry about in program.

toufic.dbouk
17th October 2013, 10:26
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow win;
win.show();
GrabThread thread;
thread.start();
qDebug() << "hello from GUI thread " << a.thread()->currentThreadId();
thread.wait(); // do not exit before the thread is completed!
return a.exec();
}

well look at your thread.wait() function... it is blocking the event loop until the thread is done.
So return a.exec() ( which enters the main event loop ) will only be executed after the thread is done , hence your GUI pop outs after the thread is done.

Good Luck.

prkhr4u
17th October 2013, 11:12
@toufic.dbouk:
I have removed the line thread.wait() and now the program is running just fine..thanks for the info
@pkj:
I have not written the exec() inside Grabthread::run()
I will keep your advice in mind.Actually don't know about event loop..will study and tell..