gracefully exit thread when working with 3rd party lib for which I don't have control
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;
Code:
//My worker class
void worker::myWork()
{
}
//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()
{
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();
}
Re: gracefully exit thread when working with 3rd party lib for which I don't have con
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,
_