C++ 如何杀死或终止一个 b​​oost 线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23558875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:29:26  来源:igfitidea点击:

How to kill or Terminate a boost Thread

c++visual-studioqtboostboost-thread

提问by Mustansar Fiaz

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

我想终止或杀死 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;   
}

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

我想在函数返回之前关闭那个 boost 线程。提前致谢。

回答by Dave McMordie

On Windows:

在 Windows 上:

TerminateThread(u.native_handle(), 0);

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

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

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...

请注意,boost 作者故意忽略了这一点,因为该行为是平台相关的并且没有明确定义。但是,您并不是唯一一个使用此功能的人......

回答by herohuyongtao

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

使用interrupt(). 此外,您应该定义中断点。线程在调用后interrupt()一到达中断点之一就会被中断。

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

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