【问题标题】:C++ What datatype is a thread_id and can it assigned to a variable?C ++什么数据类型是thread_id,可以分配给变量吗?
【发布时间】:2016-05-07 23:36:19
【问题描述】:

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

使用#include <thread> 库。

【问题讨论】:

  • 您使用的是哪个线程库?
  • 类型为std::thread::id。是的can be assigned。当您好奇时,请使用搜索 ;)
  • 啊,我做到了,而且这似乎...经常发生?像线程::id == 线程::id?这是否意味着线程的特定成员也是线程内的 ADT?我想也许它更接近原始数据类型?
  • 这是一个类。 Nested class 的 std::thread。它有一些operators overloaded,如参考中所述,因此它看起来像一个原始类型。什么是 ADT?
  • @Drop OOOOOOooooooohhhhhh.... 现在这很有意义。谢谢!

标签: c++ multithreading c++11 thread-synchronization


【解决方案1】:

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,它可以(如果实现支持)返回一个标识符,您可以将其用于特定于操作系统的功能

Online demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多