线程id分配有多整齐

How tidy is thread id assignment?

本文关键字:id 分配 线程      更新时间:2023-10-16

我做了以下实验:

#include <iostream>
#include <thread>
void t()
{
    std :: cout << std :: this_thread :: get_id() << std :: endl;
}
void f()
{
    std :: cout << std :: this_thread :: get_id() << std :: endl;
}
int main()
{
    std :: cout << std :: this_thread :: get_id() << std :: endl;
    for(unsigned int i = 0; i < 1000; i++)
    {
        std :: thread d(t);
        d.join();
        std :: thread g(f);
        g.join();
    }
}

并注意到thread_id s的结果列表总是相同的。换句话说,在这种情况下,只要线程被连接并重新打开,thread_id就会不断地被重新分配。

现在,我能有任何形式的确定性,这将永远发生吗?或者一个thread_id只分配一次,然后总是以随机的方式分配不同的thread_id ?

不,你不能假设它总是相同的。在VS2015上,我得到以下内容:

...
2444
18472
29912
25180
6612
29440
13220
4684
14004
12388
16424
26320
25948
28076
30904
6396
1160
4228
...

这里有一些文档:http://en.cppreference.com/w/cpp/thread/thread/id

重点是我的

thread::id类是一个轻量级的、可复制的类,作为std::thread对象的唯一标识符。

该类的实例也可以保存不代表任何线程的特殊distinct值。一旦线程结束,std::thread::id 的值可以被另一个线程重用

这个类设计用于关联容器(包括有序容器和无序容器)中的键。