Naming Linux Threads

Here’s a quickie tip for all you C/C++ developers working on multithreaded apps in Linux. If you find yourself frequently scratching your head over which thread is which when monitoring your application using, say, top or strace, try naming your threads!

#include 

void myThreadFunc()
{
    prctl( PR_SET_NAME, "WorkerThread", 0, 0, 0 );
    // Other interesting code
}

At runtime, you can easily correlate thread names with an ID by taking a peek at /proc/[PID]/task/[THREADID]/stat or /proc/[THREADID]/stat. Just make sure your thread names are 16 characters or less (see PR_SET_NAME documentation). And it probably goes without saying, but call prctl() from within the thread you wish to name.

This little trick saved my butt the last couple of days. Maybe it’ll help you too.

Leave a Reply

Your email address will not be published. Required fields are marked *

32 − 31 =