Does std::this_thread::get_id work independently of how threads are created?

Viewed 323

Does std::this_thread::get_id work independently of how the thread that calls it has been created (whether that's via std::thread or OpenMP or pthreads or the OS Api)?

1 Answers

Yes.

Threads have ids no matter if represented by a std::thread or some other abstraction.

Not as a proof, but as illustration you can remove any std::thread from the std::this_thread::get_id example from cppreference:

#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();
}

to see that it prints the id of the main thread.

The standard says 32.4.4#1:

Returns: An object of type thread​::​id that uniquely identifies the current thread of execution. No other thread of execution has this id and this thread of execution always has this id. The object returned does not compare equal to a default constructed thread​::​id.

Related