Waqar
Waqar

Reputation: 9366

What is std::jthread in c++20?

  1. What advantages does it offer over std::thread?
  2. Will it deprecate the existing std::thread?

Upvotes: 52

Views: 22182

Answers (2)

SajadBlog
SajadBlog

Reputation: 585

Here are the key differences between std::jthread and std::thread:

  1. Automatic Joining:

    • In the case of std::jthread, the thread is automatically joined when its destructor is called.
    • For 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).
    • Using std::jthread eliminates the need to explicitly join threads and helps in avoiding issues related to incomplete thread termination.
  2. Enhanced Control with std::stop_token:

    • std::jthread provides more control over thread execution through the use of std::stop_token.
    • The 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.
    • For further details on 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

Nicol Bolas
Nicol Bolas

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

Related Questions