Reputation: 9366
std::thread
?std::thread
?Upvotes: 52
Views: 22182
Reputation: 585
Here are the key differences between std::jthread
and std::thread
:
Automatic Joining:
std::jthread
, the thread is automatically joined when its destructor is called.std::thread
, if the thread is still joinable upon destruction, it leads to a call to std::terminate
, potentially causing errors in applications (not terminating all threads).std::jthread
eliminates the need to explicitly join threads and helps in avoiding issues related to incomplete thread termination.Enhanced Control with std::stop_token
:
std::jthread
provides more control over thread execution through the use of std::stop_token
.std::stop_token
is a mechanism to send a stop request to the thread's execution. It operates as a request, allowing for controlled termination if properly handled within the thread's execution.std::stop_token
, you can refer to the official documentation.In summary, std::jthread
simplifies thread management by automatically handling joining during destruction and offers additional control over thread execution using std::stop_token
.
Upvotes: 6
Reputation: 473946
std::jthread
is like std::thread
, only without the stupid. See, std::thread
's destructor would terminate the program if you didn't join
or detach it manually beforehand. This led to tons of bugs, as people would expect it to join on destruction.
jthread
fixes this; it joins on destruction by default (hence the name: "joining thread"). It also supports a mechanism to ask a thread to halt execution, though there is no enforcement of this (aka: you can't make another thread stop executing).
At present, there is no plan to deprecate std::thread
.
Upvotes: 72