Skip to content
systemcoding.dev
Concurrency

Set Thread Names for Debugging with pthread_setname_np

Name threads with pthread_setname_np so gdb, top -H and /proc show readable names. Covers the 15-character limit, ERANGE, prctl and C++ and Rust.

7 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the C, LLVM and Arm logos.

Open top -H on a busy service and you see forty rows with the same name, the name of the executable. Attach gdb and info threads lists thread after thread labeled with nothing but a number and an address. Naming your threads costs one line each and turns that wall of identical rows into net-rx, log-flush and worker-3, which is the difference between a five-minute diagnosis and an hour of guessing. This post covers pthread_setname_np on Linux with glibc 2.41, the length limit that trips everyone, where the names show up, and the equivalents in C++ and Rust.

The API

The call is a GNU extension, so it needs _GNU_SOURCE defined before any include:

c
int pthread_setname_np(pthread_t thread, const char *name);
int pthread_getname_np(pthread_t thread, char *name, size_t size);

Both return 0 on success and an error number on failure, like the rest of the pthread functions. The _np suffix marks them non-portable: they are not part of POSIX. The man page documents the details used below.

The length limit is the part that surprises people. The name may be at most 16 bytes, and that count includes the terminating null byte, so you get 15 visible characters. A longer string makes pthread_setname_np fail with ERANGE and leaves the name unchanged. It does not truncate for you. The limit comes from the kernel, which stores the name in the comm field of the task.

Name a thread from inside itself

A thread can name itself with pthread_self():

named_thread.cc
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <string.h>

static void *worker(void *arg)
{
    (void)arg;

    int rc = pthread_setname_np(pthread_self(), "log-flush");
    if (rc != 0) {
        fprintf(stderr, "setname failed: %s\n", strerror(rc));
        return NULL;
    }

    char name[16];
    pthread_getname_np(pthread_self(), name, sizeof name);
    printf("this thread is named %s\n", name);
    return NULL;
}

int main(void)
{
    pthread_t t;
    pthread_create(&t, NULL, worker, NULL);
    pthread_join(t, NULL);
    return 0;
}

Build with gcc -Wall -Wextra -pthread -o named_thread named_thread.c:

Text
this thread is named log-flush

The buffer passed to pthread_getname_np must be at least 16 bytes. A smaller buffer gives ERANGE again. Declaring char name[16] is the idiomatic size, and glibc exposes no named constant for it in older releases, so a literal with a comment is normal.

Name a thread from its creator

You can also name a thread from the outside, after pthread_create returns, by passing the new thread's handle:

c
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_setname_np(t, "worker-1");

This works on Linux, but it races with the thread's own start: the thread may run for a moment under the inherited name. A thread that must be named from its first instruction should name itself. Also, naming another thread means writing to its entry under /proc/self/task/<tid>/comm, which can fail if the thread has already exited, so check the return code.

The 15-character limit in practice

Generate names from an index and keep them short:

worker_names.cc
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <string.h>

static void *worker(void *arg)
{
    int id = *(int *)arg;
    char name[16];
    int n = snprintf(name, sizeof name, "worker-%d", id);
    if (n < 0 || (size_t)n >= sizeof name)
        return NULL;                 /* would not fit */

    int rc = pthread_setname_np(pthread_self(), name);
    printf("worker %d: setname -> %s\n", id, rc == 0 ? "ok" : strerror(rc));
    return NULL;
}

int main(void)
{
    pthread_t t;
    int id = 3;
    pthread_create(&t, NULL, worker, &id);
    pthread_join(t, NULL);

    int rc = pthread_setname_np(pthread_self(), "a-name-that-is-far-too-long");
    printf("long name: %s\n", rc == 0 ? "ok" : strerror(rc));
    return 0;
}
Text
worker 3: setname -> ok
long name: Numerical result out of range

strerror(ERANGE) prints "Numerical result out of range" on glibc. The snprintf guard in worker catches the same problem before the call, which is useful when the name is built from user data. A common convention is a short subsystem prefix and an index: rx-0, rx-1, db-pool-12.

Where the names appear

Because the name lives in the kernel's task structure, every Linux tool sees it:

ToolHow to see it
top -HThe COMMAND column per thread
ps -L -o tid,comm -p <pid>One row per thread with its name
/proc/<pid>/task/<tid>/commThe raw name, one file per thread
gdbinfo threads shows it as the quoted name
perfPer-thread breakdown in reports
Core dumps and crash reportsThe comm field of each thread

An example from ps for a process with three named threads, on a machine where the process ID is 5120:

Text
    TID COMMAND
   5120 named_thread
   5121 log-flush
   5122 worker-1

The IDs will differ on your machine. The main thread keeps the executable's name, which you can change with pthread_setname_np(pthread_self(), "main-loop") from the main thread.

In gdb, the listing looks like this:

Text
(gdb) info threads
  Id   Target Id                                   Frame
* 1    Thread 0x7ffff7d8a740 (LWP 5120) "named_thread" main () at named_thread.c:27
  2    Thread 0x7ffff7d89640 (LWP 5121) "log-flush" 0x00007ffff7e1b0e6 in ?? ()

The quoted string after the thread ID is the name. Tracing a hang across forty identical threads is impossible, but with names you can run thread apply all bt and immediately find the one called db-pool-7 blocked in futex_wait.

The prctl alternative

On Linux there is a lower-level way to name the calling thread: prctl(PR_SET_NAME, "name"). It sets the same comm field, takes the same 16-byte limit (longer strings are silently truncated rather than rejected), and affects only the caller. pthread_setname_np is a wrapper that also lets you name other threads. Prefer the pthread function in new code, and use prctl where you are not linking against pthreads. See prctl(2).

C++ and Rust

C++ has no standard function for naming a thread. With libstdc++ you reach the native handle:

cpp
std::thread t(work);
pthread_setname_np(t.native_handle(), "net-rx");

This is Linux-specific, so wrap it in a small helper and guard it by platform. C++20's std::jthread exposes native_handle() the same way.

Rust has it built in. thread::Builder::name names the thread and, on Linux, passes the name to the operating system, so the tools above show it:

rust
let handle = std::thread::Builder::new()
    .name("net-rx".to_string())
    .spawn(|| { /* ... */ })?;

Rust truncates a longer name to what the platform allows rather than failing. The name also appears in panic messages: thread 'net-rx' panicked at ....

When this does not help

Naming does not work around a design problem. If your program creates thousands of short-lived threads, the names will not stay meaningful, and the right fix is a thread pool. On other platforms the call differs: macOS only lets a thread name itself, with a one-argument pthread_setname_np, and Windows uses SetThreadDescription. Code that must run on all three needs a wrapper.

Naming conventions for a real service

A name is only useful if it can be searched. A few conventions pay off in a service with many threads.

Put the role first and the index last, with a short separator: rx-0, rx-1, db-pool-12. Tools sort by name, so related threads sit together in top -H and ps -L output, and a glob such as db-pool-* matches all of them in a log filter. Keep the role short enough to leave room for the index inside 15 characters; db-pool-12 uses 10.

Use the same names in your logs. If a log line prefix prints the thread name (pthread_getname_np once, cached in a thread-local), a log entry and a gdb backtrace speak the same language, and a stuck thread named net-rx-3 in a core dump can be matched to the log lines it wrote. For a thread pool, the worker's name is set once at thread start, not per task, so a task that wants to leave a trace should log its own identifier instead.

Finally, do not put secrets or per-request data in thread names. The name is visible to every user who can read /proc/<pid>/task/<tid>/comm, which includes other accounts on a shared machine, and it appears in crash reports that may be shared outside the team.

Also inDebugging
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.