C++什么数据类型是thread_id,它能分配给变量吗

C++ What datatype is a thread_id and can it assigned to a variable?

本文关键字:分配 变量 id 数据类型 什么 thread C++      更新时间:2023-10-16

我很好奇线程的数据类型是什么,以及它是否可以分配给变量,这样做是否明智/有用。

使用#include <thread>库。

std::thread是表示单个执行线程的类。

它本身并不是一个操作系统线程。它只是代表它。

您可以创建线程类型的对象:

thread t1(foo);

你可以移动构造这样的对象,也可以移动分配这样的对象:

thread t2,t3;
t3=thread(foo);   // move assignement t3 start function foo() now
t2=move(t3);      // t2 takes over what t3 was representing 

但你不能复制线程:

//t2=t3;          // not possible to copy threads; you have to move them 

线程的标识可以通过thread::id类型(依赖于实现的类型)的值来完成。然而,native_handle()也返回了一个thread::native_handle_type,它可以(如果实现支持的话)返回一个可以用于操作系统特定功能的标识符

在线演示