Daily bit(e) of C++ | std::jthread

Šimon Tóth
May 2, 2024

Daily bit(e) of C++ ♻️8, The C++20 joining thread handle: std::jthread.

The C++20 standard introduced a new version of the standard thread handle, std::jthread (joining thread).

When an instance of a std::thread is destroyed while holding a thread, it will automatically call std::terminate. We, therefore, have to manually call join() or detach().

The std::jthread will instead automatically join the held thread in its destructor.

#include <thread>
#include <chrono>

{
auto t = std::thread([]{
using namespace std::literals;
std::this_thread::sleep_for(200ms);
});
// Required
t.join();
} // end of scope, t is destroyed

{
auto t = std::jthread([]{
using namespace std::literals;
std::this_thread::sleep_for(200ms);
});
} // end of scope, t is joined and then destroyed

// Start a thread and immediately join.
std::jthread([]{});
// Start a thread and immediately call std::terminate.
std::thread([]{});

Open the example in Compiler Explorer.

--

--

Šimon Tóth

I'm an ex-Software Engineer and ex-Researcher focusing on providing free educational content.