首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ std::this_thread::get_id()传递给cout

C++ std::this_thread::get_id()传递给cout
EN

Stack Overflow用户
提问于 2017-10-10 08:35:27
回答 1查看 319关注 0票数 0

当使用std::this_thread::get_id()编译器在CodeBlocks上使用c++11时,线程号从2开始。每次我运行下面的代码时,它都会打印线程2-6而不是0- 4。为什么?

是否有可能在后台运行的其他c++应用程序正在使用线程ID 1和2?这是什么巫术?

代码语言:javascript
复制
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

std::mutex m;

class TClass
{
    public:
        void run()
        {
            m.lock();
            cout << "Hello, I'm thread " << std::this_thread::get_id() << endl;
            m.unlock();
        }
};

int main()
{
    TClass tc;
    std::thread t[5];
    for (int i=0; i<5; i++)
    {
        t[i] = std::thread(&TClass::run, &tc);
    }

    for (int i=0; i<5; i++)
    {
        t[i].join();
    }
    cout << "All threads terminated." << endl;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-10 08:38:08

不能保证std::this_thread::get_id()返回的值。您不能假设该值将从零开始或将是顺序的。这是未指定的

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46662117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档