std::jthread::join(3)

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

🌸 std::jthread::join(3) 🌸

okay bestie, welcome to the C++ Standard Libary manual β€” yes, that's the manual name, and we're keeping it cute and exact. This page is all about std::jthread::join, and it's lowkey iconic. πŸ’…

πŸŽ€ NAME πŸŽ€

std::jthread::join β€” std::jthread::join (that's the whole NAME, bestie, no extra lore πŸ’–).

πŸ¦‹ Synopsis πŸ¦‹

void join();  (since C++20)

Blocks the current thread until the thread identified by *this finishes its execution.

The completion of the thread identified by *this synchronizes with the corresponding successful return from join().

No synchronization is performed on *this itself. Concurrently calling join() on the same jthread object from multiple threads constitutes a data race that results in undefined behavior.

🚨 bestie, fr fr, that means: don't have multiple threads calling join() on the same jthread object at the same time. It's a data race, and data races are undefined behavior. Not cute. Not slay. πŸ™ˆ

πŸ’œ Parameters πŸ’œ

Parameters: none. Literally none, bestie. ✨

🌈 Return value 🌈

Return value: none. She returns void, periodt. 🫢

⭐ Postconditions ⭐

joinable() is false. That's the postcondition, and it ate. βœ…

πŸ”₯ Exceptions πŸ”₯

std::system_error if an error occurs.

πŸ’€ Error conditions πŸ’€

  • resource_deadlock_would_occur if this->get_id() == std::this_thread::get_id() (deadlock detected).
  • no_such_process if the thread is not valid.
  • invalid_argument if joinable() is false.

πŸ“ Example πŸ“

// Run this code

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

void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
    std::cout << "starting first helper...\n";
    std::jthread helper1(foo);

    std::cout << "starting second helper...\n";
    std::jthread helper2(bar);

    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    helper2.join();

    std::cout << "done!\n";
}

Output:

starting first helper...
starting second helper...
waiting for helpers to finish...
done!

πŸ‘‘ References πŸ‘‘

  • C++23 standard (ISO/IEC 14882:2023):
    • 33.4.4.3 Members [thread.jthread.mem]
  • C++20 standard (ISO/IEC 14882:2020):
    • 32.4.3.2 Members [thread.jthread.mem]

🧚 See also 🧚

  • detach β€” permits the thread to execute independently from the thread handle (public member function).
  • joinable β€” checks whether the thread is joinable, i.e. potentially running in parallel context (public member function).
  • C documentation for thrd_join.

mwah πŸ’‹ β€” source/version: http://cppreference.com; date: 2024.06.10; page: std::jthread::join(3). πŸŽ€βœ¨

πŸ“¦ where this page comes from