如何杀死或终止一个boost线程

How to kill or Terminate a boost Thread

本文关键字:一个 boost 线程 何杀死 终止      更新时间:2023-10-16

我想终止或杀死boost线程。代码在这里:

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

我想在返回函数之前关闭该boost线程。

Windows:

TerminateThread(u.native_handle(), 0);

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

pthread_cancel(u.native_handle());

pthread_kill(u.native_handle(), 9);

注意,boost作者故意省略了这一点,因为该行为依赖于平台并且没有很好地定义。但是,您并不是唯一使用此功能的人……

使用interrupt()。另外,您应该定义中断点。线程调用interrupt()后,一旦到达中断点之一,线程将被中断。

u.interrupt();

更多信息:

调用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()