如何杀死或终止一个提升线程

Mus*_*iaz 7 c++ qt boost boost-thread visual-studio

我想终止或杀死提升线程.代码在这里:

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;   
}
Run Code Online (Sandbox Code Playgroud)

我想在返回函数之前关闭该boost线程.提前致谢.

Dav*_*die 15

在Windows上:

TerminateThread(u.native_handle(), 0);
Run Code Online (Sandbox Code Playgroud)

在Linux/QNX/UNIX /任何支持pthread的平台上:

pthread_cancel(u.native_handle());
Run Code Online (Sandbox Code Playgroud)

要么

pthread_kill(u.native_handle(), 9);
Run Code Online (Sandbox Code Playgroud)

请注意,boost作者故意将其排除在外,因为行为依赖于平台而且定义不明确.但是,你并不是唯一一个能够达到此功能的人......


her*_*tao 14

使用interrupt().此外,您应该定义中断点.interrupt()一旦到达其中一个中断点,线程将在调用后被中断.

u.interrupt();
Run Code Online (Sandbox Code Playgroud)

更多信息:

调用interrupt()只是在该线程的线程管理结构中设置一个标志并返回:它不等待线程实际被中断.这很重要,因为线程只能在其中一个预定义的中断点中断,并且线程可能永远不会执行中断点,因此永远不会看到请求.目前,中断点是:

  • 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()

  • 很好的答案.提供一些上下文:没有办法可靠地杀死一个线程; 甚至没有像[`TerminateThread`]这样的平台特定设施(http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v = vs.85).aspx),而不会破坏整个过程的稳定性.合作是唯一的方法. (6认同)