std::thread::id 跨进程是否唯一?

问题描述 投票:0回答:3

根据我的经验,结果似乎是

std::this_thread::get_id()

跨进程是唯一的:一个进程的 id 与另一个进程不同。

这是标准保证的吗?

c++11 stl stdthread
3个回答
5
投票

std::thread 在支持 pthreads 的环境中在 pthreads 之上实现。所以它变得没有(可移植)保证。

来自 pthread_self 手册:

线程 ID 仅在进程内保证唯一。 A
线程 ID 可以在加入终止的线程后重用,或者 一个分离的线程已终止。


2
投票

标准授予者线程 ID 在不同线程中是唯一的,它还表示终止的线程 ID 可以被重用。它不指定进程,也不承认进程的存在,因此,它不保证进程之间的唯一性。

30.3.1.1

  1. thread::id 类型的对象为每个执行线程提供唯一标识符,并为所有线程对象提供一个不同的值 不代表执行线程 (30.3.1)。每个线程的 执行有一个关联的 thread::id 对象,该对象不等于 任何其他执行线程的 thread::id 对象,但不是 等于任何不存在的 std::thread 对象的 thread::id 对象 代表执行线程。
  2. thread::id 应该是一个普通可复制的类(第 9 条)。库可以重用已终止线程的 thread::id 的值 无法再加入。

该标准还隐藏了 thread::id 的实现,它可以是 int 或其他东西。


0
投票

我经常使用图形 API,其中许多图形 API 使用

thread_local
存储来存储特定于线程的内容。

问题是,当一个线程终止并再次启动时,它可能具有与前一个线程相同的

thread::id
,但任何
thread_local
存储不再存在,因此我的图形API中的一些全局缓存/上下文变得陈旧然后坠毁了。

我没有使用

this_thread::get_id()
或 pthread,而是创建了自己的原子计数器,并将其存储在
thread_local
存储中:

static int getCurrentThreadId() {
  static std::atomic<int> threadCounter = 0;
  static thread_local int thisThreadId = -1;
  if (thisThreadId == -1) {
    thisThreadId = threadCounter++;
  }
  return thisThreadId;
}

ID 从

0
开始,每次新线程访问
getCurrentThreadId()
时,它都会自行递增。

© www.soinside.com 2019 - 2024. All rights reserved.