Why is this an issue?
std::jthread
, introduced in C++20, is a wrapper around std::thread
. This way, it has the same functionalities as
std::thread
, making the substitution really straightforward, while adding two interesting behaviors:
- It joins by default in its destructor. If a
std::thread
was not joined or detached before being destroyed, a call to
std::terminate
was made. This can’t happen with std::jthread
.
- It can be canceled or stopped in some situations by calling
request_stop()
This rule raises an issue as soon as std::thread
is used.
Noncompliant code example
void backgroundTask();
int main() {
std::thread t(backgroundTask); // Noncompliant
t.join();
}
Compliant solution
void backgroundTask();
int main() {
std::jthread jt(backgroundTask);
}
Resources