PDA

View Full Version : QT Thread termination Pls help



dya
18th July 2011, 06:17
Hi all,

I am new to QT programming. I have an application which consists of a thread for file write function which takes time. The user has option also to cancel the file write.I have implemented the cancel button using QT thread::terminate for stopping the file write,but Iam getting segmentation fault when i press the cancel button.Can anyone comment regarding this,is there any other option other than thread termination,pls help.

Santosh Reddy
18th July 2011, 06:30
You could use exit() or stop() for stopping a thread. To comment on your problem you may need to provide some more information. Please post a sample of your thread (or details like, does it use even loop, signals, slots, thread ownership, thread children etc..), and how exactly you are starting the thread.

dya
18th July 2011, 07:36
Pls see my code snippet below,I tried exit() also but it gives segfault

WriteThread::run()
{
Fwrite();//file write function takes time to complete
}

Main::Cancel_clicked
{
WriteThread->terminate () ;
WriteThread->wait();
}

Main::Write_clicked()
{
WriteThread-> start();
}

Santosh Reddy
18th July 2011, 07:47
terminating Fwrite() abruptly is not a good idea, it would be better to write chunks of data to file, and between writing chunks check for the cancel from the user, and when cancel is detected, you can close the handles properly and exit the thread, this way it will safe. terminating Fwrite() abruptly, may not be safe.

Also there is somethings you can check for, are there any handles in Fwrite() which use else were?

I would recommend to have a event loop in the thread, and you start a timer for writing chunks into file, this way you can send a cancel write signal to thread, and thread will clean up properly and exit / close itself.

moreover you can read the terminate() documentation (http://doc.qt.nokia.com/4.7/qthread.html#terminate), and understand what would go wrong