std::jthread::jthread(3)

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

πŸ’… std::jthread::jthread(3) πŸ’…

okay bestie, welcome to the C++ Standard Libary manual, section 3 β€” the page title is literally std::jthread::jthread, and we're about to vibe-check this constructor like it owes us money. periodt. ✨

πŸŽ€ NAME πŸŽ€

std::jthread::jthread - std::jthread::jthread

yes, that's the name twice. the manpage said what it said. πŸ’…

✨ Synopsis ✨

here's the overload lineup:

jthread() noexcept;                        (1) (since C++20)
jthread( jthread&& other ) noexcept;       (2) (since C++20)
template< class F, class... Args >         (3) (since C++20)
explicit jthread( F&& f, Args&&... args );
jthread( const jthread& ) = delete;        (4) (since C++20)

Constructs new std::jthread object. lowkey the whole assignment. 🫢

1) Creates new std::jthread object which does not represent a thread. empty jthread energy.

2) Move constructor. Constructs the std::jthread object to represent the thread of execution that was represented by other. After this call other no longer represents a thread of execution. the thread said "it's not me, it's move semantics."

3) Creates new std::jthread object and associates it with a thread of execution.

The new thread of execution starts executing:

std::invoke(decay-copy(std::forward<F>(f)), get_stop_token(), (until C++23)
            decay-copy(std::forward<Args>(args))...)
std::invoke(auto(std::forward<F>(f)), get_stop_token(),       (since C++23)
            auto(std::forward<Args>(args))...)

if the expression above is well-formed, otherwise starts executing:

std::invoke(decay-copy(std::forward<F>(f)),           (until C++23)
            decay-copy(std::forward<Args>(args))...).
std::invoke(auto(std::forward<F>(f)),                 (since C++23)
            auto(std::forward<Args>(args))...).

The calls of decay-copy are evaluated (until C++23). The values produced by auto are materialized (since C++23) in the current thread, so that any exceptions thrown during evaluation and copying/moving of the arguments are thrown in the current thread, without starting the new thread.

These overloads participate in overload resolution only if std::remove_cvref_t<F> is not the same type as std::jthread.

If any of the following is false, the program is ill-formed:

  • std::is_constructible_v<std::decay_t<F>, F>
  • (std::is_constructible_v<std::decay_t<Args>, Args> && ...)
  • std::is_invocable_v<std::decay_t<F>, std::decay_t<Args>...> || std::is_invocable_v<std::decay_t<F>, std::stop_token, std::decay_t<Args>...>

The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f on the new thread of execution.

4) The copy constructor is deleted; threads are not copyable. No two std::jthread objects may represent the same thread of execution. no cap, no copies, no shared thread identity.

πŸ¦‹ Parameters πŸ¦‹

  • other β€” another std::jthread object to construct this std::jthread object with
  • f β€” Callable object to execute in the new thread
  • args β€” arguments to pass to the new function

πŸ’€ Postconditions πŸ’€

  • 1) get_id() equal to std::jthread::id() (i.e. joinable() returns false) and get_stop_source().stop_possible() is false.
  • 2) other.get_id() equal to std::jthread::id() and get_id() returns the value of other.get_id() prior to the start of construction.
  • 3) get_id() not equal to std::jthread::id() (i.e. joinable() returns true), and get_stop_source().stop_possible() is true.

😭 Exceptions 😭

  • 3) std::system_error if the thread could not be started. The exception may represent the error condition std::errc::resource_unavailable_try_again or another implementation-specific error condition.

🌸 Notes 🌸

The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with std::ref or std::cref). bestie, if you need a reference, wrap it β€” don't just yeet a raw reference.

Any return value from the function is ignored. If the function throws an exception, std::terminate is called. In order to pass return values or exceptions back to the calling thread, std::promise or std::async may be used. so your return value is giving ignored main character, and exceptions are giving terminate. use promise/async if you need receipts.

🌈 Example 🌈

okay bestie, run this code:

// Run this code

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

using namespace std::literals;

void f1(int n)
{
    for (int i = 0; i < 5; ++i)
    {
        std::cout << "Thread 1 executing\n";
        ++n;
        std::this_thread::sleep_for(10ms);
    }
}

void f2(int& n)
{
    for (int i = 0; i < 5; ++i)
    {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(10ms);
    }
}

class foo
{
public:
    void bar()
    {
        for (int i = 0; i < 5; ++i)
        {
            std::cout << "Thread 3 executing\n";
            ++n;
            std::this_thread::sleep_for(10ms);
        }
    }
    int n = 0;
};

class baz
{
public:
    void operator()()
    {
        for (int i = 0; i < 5; ++i)
        {
            std::cout << "Thread 4 executing\n";
            ++n;
            std::this_thread::sleep_for(10ms);
        }
    }
    int n = 0;
};

int main()
{
    int n = 0;
    foo f;
    baz b;
    std::jthread t0; // t0 is not a thread
    std::jthread t1(f1, n + 1); // pass by value
    std::jthread t2a(f2, std::ref(n)); // pass by reference
    std::jthread t2b(std::move(t2a)); // t2b is now running f2(). t2a is no longer a thread
    std::jthread t3(&foo::bar, &f); // t3 runs foo::bar() on object f
    std::jthread t4(b); // t4 runs baz::operator() on a copy of object b
    t1.join();
    t2b.join();
    t3.join();
    std::cout << "Final value of n is " << n << '\n';
    std::cout << "Final value of f.n (foo::n) is " << f.n << '\n';
    std::cout << "Final value of b.n (baz::n) is " << b.n << '\n';
    // t4 joins on destruction
}

Possible output:

Thread 2 executing
Thread 1 executing
Thread 4 executing
Thread 3 executing
Thread 3 executing
Thread 4 executing
Thread 2 executing
Thread 1 executing
Thread 3 executing
Thread 1 executing
Thread 4 executing
Thread 2 executing
Thread 3 executing
Thread 1 executing
Thread 4 executing
Thread 2 executing
Thread 3 executing
Thread 1 executing
Thread 4 executing
Thread 2 executing
Final value of n is 5
Final value of f.n (foo::n) is 5
Final value of b.n (baz::n) is 0

πŸ’€ Defect reports πŸ’€

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • DR: LWG 3476
  • Applied to: C++20
  • Behavior as published: overload (3) directly required (the decayed types of) F and the argument types to be move constructible
  • Correct behavior: removed these requirements^[1]
  1. ↑ The move-constructibility is already indirectly required by std::is_constructible_v.

🫢 See also 🫢

  • constructor β€” constructs new thread object (public member function of std::thread)
  • C documentation for thrd_create

source/version/date check: http://cppreference.com, 2024.06.10, std::jthread::jthread(3). that's the whole page, bestie β€” go forth and construct threads responsibly. πŸ’…βœ¨

πŸ“¦ where this page comes from