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

查看:105
本文介绍了如何在 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.

推荐答案

  1. 您可以从任何线程调用 std::terminate() 并且您所指的线程将强制结束.

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

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