std::thread线程命名

也可以参考我另外一篇文章,另外一篇更详细些。为线程设置名字的最大的好处是在程序出错时,它会出现在 GDB 的出错信息里,可以更快地定位问题。

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

#include 
#include 

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;
}

你可能感兴趣的:(linux,C语言,c++,开发语言)