39

C++ 设置 std::thread 线程名称

 2 years ago
source link: https://zhiqiang.org/coding/cpp-set-thread-name.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++ 设置 std::thread 线程名称

作者: 张志强

, 发表于 2020-09-02

, 共 584 字 , 共阅读 6 次

有两种方法,一种在线程的调用函数内部设置,还有一种是在外部对指定线程变量做设置。

#include <thread>
#include <pthread.h>

int main() 
{
    std::thread _([]() {
        std::string name = "abccccccccccccc";

        // 意设置的线程名字不能超过15个字符。
        pthread_setname_np(pthread_self(), name.substr(0, 15).c_str()); 

        // other works
    });

    std::thread t([]() {
        // other works
    });

    std::string name = "xxxxxxxxxxxxxxxxxx";
    pthread_setname_np(t.native_handle(), name.substr(0, 15).c_str()); 

    return 0;
}

为线程设置名字之后最大的好处是,程序出错在 GDB 的出错信息里,可以看到有意义的线程名称,从而更快地定位问题。

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK