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;

Qt Code:
  1. //My worker class
  2. void worker::myWork()
  3. {
  4. QThread::sleep(10);
  5. }
  6.  
  7.  
  8. //main class
  9. Widget::Widget()
  10. {
  11. // QThread mythread & worker m_worker; are the class members of Widget
  12.  
  13. m_worker.moveToThread(&mythread);
  14. connect(&mythread, SIGNAL(started()), &m_worker, SLOT(myWork()));
  15. mythread.start();
  16.  
  17. killThread();
  18. }
  19.  
  20. void Widget::killThread()
  21. {
  22. QThread::sleep(3);
  23. mythread.terminate();
  24. }
To copy to clipboard, switch view to plain text mode 

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();
}