How do I terminate a thread in C++11?(如何在 C++11 中终止线程?)
问题描述
我不需要正确终止线程,或者让它响应终止"命令.我有兴趣使用纯 C++11 强行终止线程.
I don't need to terminate the thread correctly, or make it respond to a "terminate" command. I am interested in terminating the thread forcefully using pure C++11.
推荐答案
- 您可以从任何线程调用 - std::terminate()并且您所指的线程将强制结束.
- You could call - std::terminate()from any thread and the thread you're referring to will forcefully end.
你可以安排 ~thread() 在目标线程的对象上执行,无需介入 join() 或 detach() 在那个对象上.这将具有与选项 1 相同的效果.
You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object.  This will have the same effect as option 1.
你可以设计一个异常,它有一个抛出异常的析构函数.然后安排目标线程在要强行终止的时候抛出这个异常.这个问题的棘手部分是让目标线程抛出这个异常.
You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.
选项 1 和 2 不会泄漏进程内资源,但它们会终止每个线程.
Options 1 and 2 don't leak intra-process resources, but they terminate every thread.
选项 3 可能会泄漏资源,但部分合作,因为目标线程必须同意抛出异常.
Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.
在 C++11(我知道)中没有可移植的方式来非合作地杀死多线程程序中的单个线程(即不杀死所有线程).没有动力设计这样的功能.
There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.
一个 std::thread 可能有这个成员函数:
A std::thread may have this member function:
native_handle_type native_handle();
您也许可以使用它来调用依赖于操作系统的函数来执行您想要的操作.例如在 Apple 的操作系统上,这个函数存在并且 native_handle_type 是一个 pthread_t.如果你成功了,你很可能会泄漏资源.
You might be able to use this to call an OS-dependent function to do what you want.  For example on Apple's OS's, this function exists and native_handle_type is a pthread_t.  If you are successful, you are likely to leak resources.
这篇关于如何在 C++11 中终止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++11 中终止线程?
 
				
         
 
            
        基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				