PDA

View Full Version : gracefully exit thread when working with 3rd party lib for which I don't have control



prasad_N
25th January 2016, 06:00
I am using QThread to do my work where I am calling some function in the 3rd party library (So I don't have any control here to put some flags & quit my thread).
Is there a way to forcefully kill thread while it is doing some heavy work.

I have below example to explain my requirement;


//My worker class
void worker::myWork()
{
QThread::sleep(10);
}


//main class
Widget::Widget()
{
// QThread mythread & worker m_worker; are the class members of Widget

m_worker.moveToThread(&mythread);
connect(&mythread, SIGNAL(started()), &m_worker, SLOT(myWork()));
mythread.start();

killThread();
}

void Widget::killThread()
{
QThread::sleep(3);
mythread.terminate();
}


In the above code, I am trying to start thread which run for 9 sec & then immediately calling a function which trying to terminate a thread in 3 sec, But the thread is terminating after 9 seconds only not immediately, so my question here is can I kill the thread in 3 sec only.


I don't want to wait till thread finish as below (which very well may take few minutes in my application).

if(m_thread.isRunning())
{
m_thread.quit();
m_thread.wait();
}

anda_skoa
25th January 2016, 09:19
Since thread's cannot be cleanly terminated or rather their resources cannot be cleanly freed when terminated, your best option is to move the uninterruptible 3rd party calculation into a helper program which you then run as a child process.

Processes can be cleanly "removed" by the operating system.

Cheers,
_