gpt4 book ai didi

c++ - std::this_thread::get_id 是否独立于线程的创建方式工作?

转载 作者:行者123 更新时间:2023-12-01 14:46:55 27 4
gpt4 key购买 nike

std::this_thread::get_id 是否独立于调用它的线程的创建方式(无论是通过 std::thread 还是 OpenMP 或 pthreads 或操作系统 API)?

最佳答案

是的。

无论线程是否由 std::thread 或其他抽象表示,线程都有 ID。

不是作为证明,而是作为说明,您可以从 cppreferencestd::this_thread::get_id 示例中删除任何 std::thread :

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>

std::mutex g_display_mutex;

void foo()
{
std::thread::id this_id = std::this_thread::get_id();

g_display_mutex.lock();
std::cout << "thread " << this_id << " sleeping...\n";
g_display_mutex.unlock();

std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
foo();
}

see它打印主线程的 ID。

标准说32.4.4#1 :

Returns: An object of type thread​::​id that uniquely identifies thecurrent thread of execution. No other thread of execution has this idand this thread of execution always has this id. The object returneddoes not compare equal to a default constructed thread​::​id.

关于c++ - std::this_thread::get_id 是否独立于线程的创建方式工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63723977/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com