std :: thread - 命名你的线程 [英] std::thread - naming your thread

查看:2383
本文介绍了std :: thread - 命名你的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的C ++有这个std :: thread类型。奇迹般有效。
现在我想给每个线程一个更容易调试的名称(像java允许你)。
使用pthread我会这样做:

The new C++ has this std::thread type. Works like a charm. Now I would like to give each thread a name for more easy debugging (like java allows you to). With pthreads I would do:

pthread_setname_np(pthread_self(), "thread_name");

但是如何使用c ++ 0x?
我知道它在Linux系统上使用pthreads,但我想让我的应用程序可移植。是否有可能?

but how can I do this with c++0x? I know it uses pthreads underneath on Linux systems, but I would like to make my application portable. Is it possible at all?

推荐答案

一个可移植的方法是维护一个名称映射, ,从 thread :: get_id()获取。或者,如注释中所建议的,您可以使用 thread_local 变量,如果您只需要从线程内访问该名称。

A portable way to do this is to maintain a map of names, keyed by the thread's ID, obtained from thread::get_id(). Alternatively, as suggested in the comments, you could use a thread_local variable, if you only need to access the name from within the thread.

如果你不需要可移植性,那么你可以从 thread :: native_handle() pthread_t c $ c>并做任何平台特定的shenanigans你喜欢的。请注意,线程命名函数中的 _np 意味着不是posix,因此它们不能保证在所有pthread实现中可用。

If you didn't need portability, then you could get the underlying pthread_t from thread::native_handle() and do whatever platform-specific shenanigans you like with that. Be aware that the _np on the thread naming functions means "not posix", so they aren't guaranteed to be available on all pthreads implementations.

这篇关于std :: thread - 命名你的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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