线程id分配有多整齐
How tidy is thread id assignment?
我做了以下实验:
#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 的值可以被另一个线程重用。这个类设计用于关联容器(包括有序容器和无序容器)中的键。
相关文章:
- 将数组的地址分配给变量并删除
- vector.resize()中的分配错误
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- Win32编译器选项和内存分配
- 函数中堆分配的效果与缺少堆分配的情况
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 获取字符串的长度并将其分配给数组
- 将地址分配给本地指针后,公共对象的变量将消失
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 堆栈分配的类类型.为什么两个 ID 实例的地址相同?
- 错误:数字常数之前的预期无限制ID:std :: array和std ::向量大小分配
- 为CListCtrl C++分配组ID
- 具有PPL和并行内存分配的线程ID
- 在std::unordered_map中分配ID后创建对象
- 在尝试使用 new 和 copy 构造函数分配内存时,在 '(' 令牌之前获取"预期的非限定 id"
- 在运行时动态分配MFC命令id
- 为类的每个实例分配唯一 ID
- CUDA:在2D网格中分配线程ID
- 线程id分配有多整齐