How to kill or Terminate a boost Thread
Asked Answered
R

2

7

I want to terminate or kill boost thread. code is here:

DWORD WINAPI  StartFaceDetector(LPVOID temp)
{   
    int j=0;
    char **argv1;
    QApplication a(j,argv1);//add some thread here  
    gui::VisualControl w;
    t=&w;
    boost::thread u(&faceThread);       
    w.show();
    a.exec();
    // I Want to close u thread here.   
    return 0;   
}

I want to close that boost thread before return of function. Thanks in Advance.

Reubenreuchlin answered 9/5, 2014 at 7:26 Comment(1)
Why are you not using QThread?Guttural
S
15

On Windows:

TerminateThread(u.native_handle(), 0);

On Linux / QNX / UNIX / any platform with pthread support:

pthread_cancel(u.native_handle());

or

pthread_kill(u.native_handle(), 9);

Note that boost authors intentionally left this out as the behaviour is platform-dependent and not well defined. However, you're not the only one to ever reach for this functionality...

Seleucia answered 19/8, 2014 at 23:27 Comment(0)
G
14

Use interrupt(). Also, you should define interruption points. Thread will be interrupted after calling interrupt() as soon as it reaches one of interruption points.

u.interrupt();

More info:

Calling interrupt() just sets a flag in the thread management structure for that thread and returns: it doesn't wait for the thread to actually be interrupted. This is important, because a thread can only be interrupted at one of the predefined interruption points, and it might be that a thread never executes an interruption point, so never sees the request. Currently, the interruption points are:

  • boost::thread::join()
  • boost::thread::timed_join()
  • boost::condition_variable::wait()
  • boost::condition_variable::timed_wait()
  • boost::condition_variable_any::wait()
  • boost::condition_variable_any::timed_wait()
  • boost::this_thread::sleep()
  • boost::this_thread::interruption_point()
Gasconade answered 9/5, 2014 at 7:35 Comment(2)
Excellent answer. To lend some context: there is no way to reliably kill a thread; not even with a platform specific facility like TerminateThread without destabilizing the entire process. Cooperative is the only way.Inextirpable
indeed even the platform API specifically mentions that TerminateThread is a final-resort type of operation kind of like a plane having to ditch in water vs. landing on a runwayBurgee

© 2022 - 2024 — McMap. All rights reserved.