PDA

View Full Version : Loop inside Qthread causes "QThread: Destroyed while thread is still running"?



zolookas
26th June 2008, 17:02
Hi, I am new to C++ and Qt and despite that i am thinking of using threads in my app. Here is an example code which outputs "." and then "QThread: Destroyed while thread is still running" error after pressing button.


class MyThread : public QThread
{
public:
void run();
};
void MyThread::run()
{
int connected=0;
while (connected==0)
{
fprintf(stderr,".");
//Do something that modifies num when usb device is connected
sleep(5);
}
}
void MainWindowImpl::on_button_clicked()
{
MyThread t;
t.start();
}
0
What can be wrong in this code? Am I not allowed to use while loop in thread?

lyuts
26th June 2008, 17:51
What are you doing this for? You just make your thread hang.

zolookas
26th June 2008, 17:59
I am doing different things, but i don't want to post a bunch of unrelated code to confuse others. I've stripped everything that is unnecessary before posting.

jpn
26th June 2008, 18:01
"MyThread t" goes out of scope and gets destructed according to normal C++ rules immediately in the end of MainWindowImpl::on_button_clicked(). You might want to allocate it on the heap instead.

zolookas
26th June 2008, 19:41
"MyThread t" goes out of scope and gets destructed according to normal C++ rules immediately in the end of MainWindowImpl::on_button_clicked(). You might want to allocate it on the heap instead.

Thanks, it worked.

If anybody wants to now exactly how i did it: i've replaced:

MyThread t;
t.start();
with

MyThread *t=new MyThread;
t->start();