<thread>

thread

public member function
<thread>

std::thread::get_id

id get_id() const noexcept;
Get thread id
Returns the thread id.

If the thread object is joinable, the function returns a value that uniquely identifies the thread.

If the thread object is not joinable, the function returns a default-constructed object of member type thread::id.

Parameters

none

Return value

An object of member type thread::id that uniquely identifies the thread (if joinable), or default-constructed (if not joinable)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// thread::get_id / this_thread::get_id
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::thread::id, std::this_thread::get_id
#include <chrono>         // std::chrono::seconds
 
std::thread::id main_thread_id = std::this_thread::get_id();

void is_main_thread() {
  if ( main_thread_id == std::this_thread::get_id() )
    std::cout << "This is the main thread.\n";
  else
    std::cout << "This is not the main thread.\n";
}

int main() 
{
  is_main_thread();
  std::thread th (is_main_thread);
  th.join();
}


Output:
This is the main thread.
This is not the main thread.

Data races

The object is accessed.

Exception safety

No-throw guarantee: never throws exceptions.

See also