如何在C ++ 11中终止线程? [英] How do I terminate a thread in C++11?

查看:2260
本文介绍了如何在C ++ 11中终止线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不需要正确终止线程,或使其响应terminate命令。我有兴趣使用纯C ++ 11强制终止线程。

解决方案


  1. 你可以从任何线程调用 std :: terminate(),你所引用的线程将强制结束。


  2. 您可以安排〜thread()在目标线程的对象上执行,而不插入 join() detach()。这将具有与选项1相同的效果。


  3. 您可以设计一个异常,它有一个抛出异常的析构函数。然后安排目标线程抛出这个异常,当它被强制终止。这个棘手的部分是让目标线程抛出此异常。


选项1和2 lt; / p>

选项3可能泄漏资源,但是部分协作,因为目标线程必须同意抛出异常。



在C ++ 11中没有可移植的方式(我知道)非协同杀死单个线程多线程程序(即不杀死所有线程)。没有动机设计这样的功能。



A std :: thread 可能有这个成员函数: / p>

  native_handle_type native_handle(); 

您可以使用它来调用依赖于操作系统的函数来做你想要的。例如在苹果的操作系统上,这个函数存在, native_handle_type 是一个 pthread_t 。如果你成功了,你很可能泄漏资源。


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.

解决方案

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

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

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

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

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.

A std::thread may have this member function:

native_handle_type native_handle();

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中终止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆