【问题标题】:How to kill or Terminate a boost Thread如何杀死或终止增强线程
【发布时间】:2014-06-26 20:31:10
【问题描述】:

我想终止或终止 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 线程。 提前致谢。

【问题讨论】:

  • 你为什么不用QThread?

标签: c++ visual-studio qt boost boost-thread


【解决方案1】:

在 Windows 上:

TerminateThread(u.native_handle(), 0);

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

pthread_cancel(u.native_handle());

pthread_kill(u.native_handle(), 9);

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

【讨论】:

    【解决方案2】:

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

    u.interrupt();
    

    More info:

    调用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 这样的平台特定设施,也不会破坏整个过程的稳定性。合作是唯一的途径。
    • 事实上,甚至平台 API 都特别提到 TerminateThread 是一种最终手段类型的操作,有点像飞机不得不在水中降落与降落在跑道上
    猜你喜欢
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多