std::this_thread::get_id(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

Okay bestie, this is the std::this_thread::get_id(3) page from the C++ Standard Libary manual πŸ’– (yes, that spelling is canon, don’t come for me). It’s short, it’s sweet, it’s literally β€œwhich thread am I?” energy.

✨ NAME ✨

std::this_thread::get_id - std::this_thread::get_id β€” yes bestie, that’s the whole name, twice. It’s giving β€œfunction so iconic they named it twice” πŸ’….

πŸŒ€ Synopsis πŸŒ€

Defined in header <thread>:

std::thread::id get_id() noexcept;  (since C++11)

Returns the id of the current thread. That’s it. That’s the whole serve 🫢.

πŸŽ€ Parameters πŸŽ€

  • (none) β€” not a single parameter, zero, zilch, nada ✨.

πŸ¦‹ Return value πŸ¦‹

The id of the current thread. Main-character thread identification, periodt πŸ‘‘.

πŸ”₯ Example πŸ”₯

// Run this code

#include <chrono>
#include <iostream>
#include <syncstream>
#include <thread>
using namespace std::chrono_literals;

void foo()
{
    std::thread::id this_id = std::this_thread::get_id();

    std::osyncstream(std::cout) << "thread " << this_id << "
       sleeping...\n";

    std::this_thread::sleep_for(500ms);
}

int main()
{
    std::jthread t1{foo};
    std::jthread t2{foo};
}

Possible output:

thread 140113018054400 sleeping...
thread 140113009661696 sleeping...

πŸ‘€ See also πŸ‘€

  • get_id returns the id of the thread β€” public member function of std::thread πŸ’œ
  • C documentation for thrd_current 🌈

Cute sign-off: source/version/date is http://cppreference.com, 2024.06.10 β€” mwah, go forth and identify your thread, bestie πŸ’‹πŸŽ€

πŸ“¦ where this page comes from