Skip to content
systemcoding.dev
Concurrency

Get the calling thread's handle with pthread_self

Use pthread_self() in glibc 2.39 to name the calling thread or detach it, and never print the opaque pthread_t as if it were an integer.

1 min read
Summarize in AI

A thread often needs to act on itself: name itself for a debugger, detach itself, or hand its own handle to someone else. pthread_self() returns the calling thread's pthread_t, which is the argument every other pthread_* call wants. On Linux with glibc 2.39 and GCC 13, compile with -pthread.

self.cc
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>

static void *worker(void *arg)
{
    char name[16];
    (void)arg;
    pthread_setname_np(pthread_self(), "worker-1");
    pthread_getname_np(pthread_self(), name, sizeof name);
    printf("thread name: %s\n", name);
    return NULL;
}

int main(void)
{
    pthread_t t;
    pthread_create(&t, NULL, worker, NULL);
    pthread_join(t, NULL);
    return 0;
}
Text
thread name: worker-1

pthread_t is an opaque type. It happens to be an unsigned integer on glibc, but POSIX only promises that it can be copied, so a printf("%lu", ...) is not portable and == is wrong; compare handles with pthread_equal. The 16-byte buffer is not arbitrary: Linux limits a thread name to 15 characters plus the terminating NUL, and pthread_setname_np returns ERANGE for a longer one. See pthread_self(3).

Taggedcpthreads
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.