gpt4 book ai didi

c++ - this_thread::get_id() 是否总是随着每个新线程的启动而递增

转载 作者:行者123 更新时间:2023-11-27 23:59:09 25 4
gpt4 key购买 nike

我可以通过以下方式将线程 ID 打印到控制台:

cout << "thread ID: "  << std::this_thread::get_id() << endl;

在此之后打印到控制台的 ID 对应于可以在 Visual Studio 2013 社区中找到的 ID:

Debug -> Windows -> Threads -> [ID column]

如果我在 Debug -> Windows -> Threads 中按此 ID 进行升序排序,我会得到线程启动的顺序吗?或者换句话说:std::this_thread::get_id() 是否总是随着每个新线程的启动而递增,还是也可以递减?

最佳答案

简短回答:,线程 ID 不一定随每个新线程递增。线程 ID 可以重复使用。


标准说

  1. An object of type thread::id provides a unique identifier for eachthread of execution and a single distinct value for all thread objectsthat do not represent a thread of execution (30.3.1). Each thread ofexecution has an associated thread::id object that is not equal to thethread::id object of any other thread of execution and that is notequal to the thread::id object of any std::thread object that does notrepresent threads of execution.

  2. thread::id shall be a triviallycopyable class (Clause 9). The library may reuse the value of athread::id of a terminated thread that can no longer be joined.

-- n4296 ; 30.3.1.1 [thread.thread.id]

它并没有说 ID 是单调递增的,它确实允许重复使用线程 ID。

您可能需要 native_handle ,这将是底层实现使用的句柄。这将对应于 MSVC 下的 Windows 线程句柄。这些是否单调递增取决于您的实现文档。

GetCurrentThreadId 的 MSDN 文档函数建议线程 ID 唯一标识一个线程,直到它终止;它没有说 ID 是否单调递增,这句话的含义似乎是它们可以被重用。

总而言之,C++ 标准不对线程 ID 的值提供任何保证。如果你想保证这一点,你需要让每个线程递增一个原子计数器,或者通过适当的同步获得一个单调递增的值。

关于c++ - this_thread::get_id() 是否总是随着每个新线程的启动而递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40418833/

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