Skip to content
systemcoding.dev
Debugging

Name threads with pthread_setname_np so GDB shows them

Give each thread a readable name with pthread_setname_np so GDB's info threads shows it, within the 15 character limit.

1 min read
Summarize in AI

In a program with a dozen workers, info threads shows only ids and frames, and you spend time working out which is which. Name them with pthread_setname_np, a glibc extension that GDB reads back from the kernel and prints in quotes. The name is set from the thread itself or from another thread that holds its handle.

c
#define _GNU_SOURCE
#include <pthread.h>

static void *worker(void *arg) {
    pthread_setname_np(pthread_self(), "net-worker");
    for (;;) pause_for_work();
    return arg;
}
Text
(gdb) info threads
  Id   Target Id                                   Frame
* 1    Thread 0x7ffff7d8a740 (LWP 4120) "app"       main () at app.c:30
  2    Thread 0x7ffff7d89700 (LWP 4124) "net-worker" 0x00007ffff7e5f1ef in pause ()

The limit is the one that bites: a Linux thread name holds 15 characters plus the terminating NUL, and glibc's pthread_setname_np returns ERANGE for a longer string instead of truncating, so the name is not set at all. Check the return value in code that builds names from ids. top -H and /proc/<pid>/task/<tid>/comm show the same name, so the work pays off outside the debugger.

On macOS the function takes only a name and applies it to the calling thread, and the BSDs call it pthread_set_name_np. The glibc interface is in the pthread_setname_np(3) manual page, and GDB 16 reads the name through /proc.

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.