C++ Thread Library - Function get_id


Advertisements

Description

It returns the thread id.

Declaration

Following is the declaration for std::thread::get_id function.

id get_id() const noexcept;

C++11

id get_id() const noexcept;

Parameters

none

Return Value

It returns the thread id.

Exceptions

No-throw guarantee − never throws exceptions.

Data races

The object is accessed.

Example

In below example for std::thread::get_id.

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

void foo() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
   std::thread sample(foo);
   std::thread::id sample_id = sample.get_id();

   std::thread sample2(foo);
   std::thread::id sample2_id = sample2.get_id();

   std::cout << "sample's id: " << sample_id << '\n';
   std::cout << "sample2's id: " << sample2_id << '\n';

   sample.join();
   sample2.join();
}

The output should be like this −

sample's id: 139887397730048
sample2's id: 139887389337344
thread.htm
Advertisements