C++ 如何在 Linux 中命名线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:14:45  来源:igfitidea点击:

How to name a thread in Linux?

c++clinuxmultithreading

提问by user9876

I have a multithreaded Linux application written in C/C++. I have chosen names for my threads. To aid debugging, I would like these names to be visible in GDB, "top", etc. Is this possible, and if so how?

我有一个用 C/C++ 编写的多线程 Linux 应用程序。我为我的线程选择了名称。为了帮助调试,我希望这些名称在 GDB、“top”等中可见。这可能吗,如果可能,如何?

(There are plenty of reasons to know the thread name. Right now I want to know which thread is taking up 50% CPU (as reported by 'top'). And when debugging I often need to switch to a different thread - currently I have to do "thread apply all bt" then look through pages of backtrace output to find the right thread).

(有很多理由知道线程名称。现在我想知道哪个线程占用了 50% 的 CPU(如 'top' 所报告的)。调试时我经常需要切换到不同的线程 - 目前我必须执行“ thread apply all bt”然后查看回溯输出页面以找到正确的线程)。

The Windows solution is here; what's the Linux one?

视窗解决方案就在这里; Linux 是什么?

回答by Fusspawn

Posix Threads?

Posix 线程?

This evidently won't compile, but it will give you an idea of where to go hunting. I'm not even sure its the right PR_command, but i think it is. It's been a while...

这显然不会编译,但它会让你知道去哪里打猎。我什至不确定它是正确的PR_命令,但我认为它是。有一阵子了...

  #include <sys/prctl.h>
  prctl(PR_SET_NAME,"<null> terminated string",0,0,0)

回答by lothar

If you are using a library like ACEthe Threadhas a way to specify the thread name when creating a new thread.

如果您使用像ACE这样的库,则Thread可以在创建新线程时指定线程名称。

BSD Unix has also a pthread_set_name_npcall.

BSD Unix 也有一个pthread_set_name_np调用。

Otherwise you can use prctlas mentioned by Fusspawn.

否则,你可以使用使用prctl由Fusspawn提及。