009 - 线程设置名字

线程设置名字

有些情况下,多线程的话,需要给线程设置名字,方便调试。

但是 C++11 虽说标准库就支持线程,但是并没有封装其他操作线程的方法,就很难受。

话不多说,show code

#include <thread>
#ifdef WIN32
#include <Windows.h>
#include <processthreadsapi.h>
#else
#include <pthread.h>
#endif

void worker()
{
    std::this_thread::sleep_for(std::chrono::seconds(5));
}

int main()
{
    std::thread foo(worker);
    auto handle = foo.native_handle();
#ifdef WIN32
    SetThreadDescription(handle, L"FOO");
#else
    pthread_setname_np(handle, "FOO");
#endif
    foo.join();
    return 0;
}

这是没有设置名字的,线程名字都是程序名字

01

这是设置了名字的,线程名字已经变成 FOO 了

02

说明:

  1. Linux 下设置名字最多 16 字节,去除 '\0' 后,就只有 15 字节了

  2. Windows 这个函数对系统版本有要求,来自MS文档

    Minimum supported clientWindows 10, version 1607 [desktop apps | UWP apps]
    Minimum supported serverWindows Server 2016 [desktop apps | UWP apps]
    Target PlatformWindows
    Headerprocessthreadsapi.h
    LibraryKernel32.lib
    DLLKernel32.dll

由于个人水平有限,文中若有不合理或不正确的地方欢迎指出改正

若文中个人文章链接打不开,请在站内寻找同名文章

文章可能更新不及时,请以个人博客处文章为准

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值