Wakan Tanka Wakan Tanka - 1 year ago 87
C++ Question

Does this_thread::get_id() always increment with every new thread started

I can print thread ID to console following way:

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

After this the IDs printed to console corresponds to IDs that can be found in Visual Studio 2013 Community under:

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

If I do ascending sort by this ID in
Debug -> Windows -> Threads
do I get the order in which threads started? Or In another words: does
always increment with every new thread started or it can also decrement?

Answer Source

The standard says

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

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

-- n4296; [thread.thread.id]

It doesn't say that the ID is monotonically increasing, and it does permit thread IDs to be reused.

It's likely that you want the native_handle, which will be the handle that the underlying implementation uses. This will correspond to the Windows thread handle, under MSVC. Whether these are monotonically increasing is a matter for your implementation's documentation.

The MSDN documentation for the GetCurrentThreadId function suggests that the thread ID uniquely identifies a thread until it terminates; it doesn't say whether the IDs are monotonically increasing, and the implication of that sentence appears to be that they may be reused.

In summary, the C++ standard provides no guarantee about the values of thread IDs. If you want to guarantee this, you'll need to have each thread increment an atomic counter, or otherwise obtain a monotonically increasing value with appropriate synchronisation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download