1

From this answer I can see that this is at least possible for MacOS.

I thought maybe this would do it:

pthread_setname_np(pthread_self(), "NEW_NAME");

This does not work as pthread_self() returns thread ID and not a pthread_t data type. I could not find a function that would return current thread pthread_t, a one that would allow to convert thread ID to pthread_t nor a one that would allow to set the current name without needing to provide the pthread_t data type as one of the arguments. Thanks.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
mega_creamery
  • 667
  • 7
  • 19

1 Answers1

0

Well, pthread_self() should already return a pthread_t, according to the pthread documentation, so the code you show seems correct. In any case, I would avoid using pthread_setname_np() since as the name implies it's non-portable.

The standard way to do this in Linux is through prctl(2):

#include <sys/prctl.h>

int prctl(int option, unsigned long arg2, unsigned long arg3,
            unsigned long arg4, unsigned long arg5);
PR_SET_NAME (since Linux 2.6.9)
       Set the name of the calling thread, using the value in the
       location pointed to by (char *) arg2.  The name can be up to
       16 bytes long, including the terminating null byte.  (If the
       length of the string, including the terminating null byte,
       exceeds 16 bytes, the string is silently truncated.)  This is
       the same attribute that can be set via pthread_setname_np(3)
       and retrieved using pthread_getname_np(3).  The attribute is
       likewise accessible via /proc/self/task/[tid]/comm, where tid
       is the name of the calling thread.

You just need to call prctl() with PR_SET_NAME as first argument and the name you want to set as second:

prctl(PR_SET_NAME, "name_here", 0, 0, 0);

Note that, as the manual states, the name cannot exceed 16 bytes (terminator included).

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • `prctl` is also non-portable, not available on windows/mingw, osx, bsd, and is not available on msvc. You should detect the correct API for this via your build configure process at compile time, and set flags to determine which to use, covering `prctl`, `pthread_setname_np` and `SetThreadDescription` depending upon availability. – braindigitalis Aug 03 '22 at 09:34
  • @braindigitalis all true, OP tagged the question with [Linux] though. – Marco Bonelli Aug 03 '22 at 09:35