0

I want to set the name of the current execution thread in C++ code; the underlying threading library is pthreads.

In case I have the std::thread handle of a thread, I can get the native pthreads handle using std::thread::native_handle, then pass this to pthread_setname_np to set the thread name.

    auto t = std::thread(call_from_thread);
    pthread_setname_np(t.native_handle(), my_thread_name.c_str());

But how can I set the thread name in cases where I do not have the std::thread handle available. For example when the thread is started by some other library, and I am writing a callback that will be executed by that thread, can I write some code within the callback that sets a custom name for the thread executing it?

I know that I can get the current thread std::thread::id object using std::this_thread::get_id. Is there a way to convert this into a pthread native handle that can then be used to set the custom thread name?

Rogue
  • 73
  • 1
  • 7
  • see https://stackoverflow.com/questions/21091000/how-to-get-thread-id-of-a-pthread-in-linux-c-program Then you can pass thread handle to pthread_getname_np – user7860670 Aug 13 '19 at 11:48
  • In Windows, you have [this](https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2019) – Michael Chourdakis Aug 13 '19 at 11:49
  • 3
    If you don't care about portability and you're using (non-portable) POSIX thread calls, why not simple use [`pthread_self`](http://man7.org/linux/man-pages/man3/pthread_self.3.html)? – Some programmer dude Aug 13 '19 at 11:52
  • @Someprogrammerdude That should be an answer. It's pretty much how they solve a similar situation in the [native_handle](https://en.cppreference.com/w/cpp/thread/thread/native_handle) example. – Ted Lyngmo Aug 13 '19 at 12:09
  • @Someprogrammerdude Thanks, this indeed answers my question. Currently I do not care about portability. Could you post this as an answer so I can mark it as answered? – Rogue Aug 13 '19 at 12:25
  • or we close it as a dup of https://stackoverflow.com/questions/16259257/c11-native-handle-is-not-a-member-of-stdthis-thread but ... no, it's not a good fit. – Ted Lyngmo Aug 13 '19 at 12:28
  • 1
    There's a LWG issue regarding getting the handle for current thread, with a trivial resolution, but for which there was no consensus for proceeding: https://cplusplus.github.io/LWG/issue2379 – eerorika Aug 13 '19 at 16:07

2 Answers2

4

Unless portability is wanted, and the target is only POSIX systems with POSIX threads, the id could easily be obtained with pthread_self.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • On the windows end you can skip `pthread_self` or std native_handles and use `SetThreadDescription(GetCurrentThread(), ...)` – Jason C Jun 25 '22 at 14:42
2

For easy copy paste I am pasting an additional answer:

pthread_setname_np(pthread_self(), "Specific name");
Mo0gles
  • 10,517
  • 2
  • 21
  • 15