How to set the thread name using std::thread lambdas in C++

Viewed 1742

I am trying to set the name of my threads for ease of profiling (in ps, top, etc.).

I usually use pthread_setname_np(pthread_self(), <THREAD_NAME>) and it works like a charm.

But the one place I cannot understand is how to do it when I'm using lambda threads.

Here's an example on what I'm trying to do.

#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <pthread.h>

int main()
{
    // vector container stores threads
    std::vector<std::thread> workers;
    for (int i = 0; i < 5; i++) {
        workers.push_back(std::thread([]()
            {                
                std::cout << "thread function\n";
            }));
    }
    std::cout << "main thread\n";

    std::for_each(workers.begin(), workers.end(), [](std::thread& t)
        {
                //I want to set the thread name for profiling
                std::string s = "mythread";
                auto handle = t.native_handle();
                pthread_setname_np(handle, s.c_str());
            t.join();
        });

    return 0;
}

This does not work. If I do top -H -p <pid> in Linux I cannot see those threads named. Thanks

0 Answers
Related