std::thread::get_id(3)

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

🌸 std::thread::get_id(3) 🌸

okay so bestie, welcome to the <pink>std::thread::get_id</pink> page β€” it's filed under the C++ Standard Libary manual (that's literally how the header spells it, not me, iykyk πŸ’…) and it's short, sweet, and honestly kinda iconic.


✨ NAME ✨

std::thread::get_id β€” literally std::thread::get_id. that's the whole name. no notes. πŸŽ€


πŸ¦‹ Synopsis πŸ¦‹

std::thread::id get_id() const noexcept;

(since C++11)

what it does: returns a value of std::thread::id identifying the thread associated with *this. that's it. that's the vibe check. ✨


πŸ“ Parameters πŸ“

(none) β€” nothing to pass in, bestie. it takes zero arguments, it's low maintenance, we love that for it. 🫢


πŸ’– Return value πŸ’–

a value of type std::thread::id identifying the thread associated with *this.

and here's the important part πŸ‘‘: if there is no thread associated, then a default constructed std::thread::id is returned. so like... the id of nobody. a ghost id. πŸ˜­πŸ’€


🌈 Example 🌈

run this code, bestie:

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

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

int main()
{
    std::thread t1(foo);
    std::thread::id t1_id = t1.get_id();

    std::thread t2(foo);
    std::thread::id t2_id = t2.get_id();

    std::cout << "t1's id: " << t1_id << '\n';
    std::cout << "t2's id: " << t2_id << '\n';

    t1.join();
    t2.join();

    std::cout << "t1's id after join: " << t1.get_id() << '\n';
    std::cout << "t2's id after join: " << t2.get_id() << '\n';
}

⭐ Possible output ⭐

t1's id: 140146221688576
t2's id: 140146213295872
t1's id after join: thread::id of a non-executing thread
t2's id after join: thread::id of a non-executing thread

see how the ids change after join()? that's the ghost-id situation from the Return value section showing up to the party 🧚 β€” once the threads are joined, get_id() hands you back a non-executing thread id. slay. πŸ’…


πŸ”₯ See also πŸ”₯

  • id β€” represents the id of a thread (public member class) πŸŽ€
  • joinable β€” checks whether the thread is joinable, i.e. potentially running in parallel (public member function) πŸ¦‹

and that's the whole page! periodt ✨ source + version + date for the record: http://cppreference.com, 2024.06.10, std::thread::get_id(3) β€” mwah, catch you in the next manpage bestie πŸ’œπŸŒΈπŸ‘‘

πŸ“¦ where this page comes from