C++20 jthread and stop token: a gentle introduction
Introduction
In my previous article on std::jthread
, I missed a few key and basic points on how C++20 jthread and stop token work together in the way how synchronization works for std::jthread
objects with automatic storage duration and how to ensure that a task assigned to std::jthread
object completes and how to prevent std::jthread
from premature suspension of execution of its task because the function it was called within exited and the destructor on std::jthread
object is called:
void foo(){
std::jthread t_foo{task, taks_param1, task_param2, ...};
...
} //t_foo::~jthread() called,
// task execution stops even if it did not finish
If you read the previous article about std::jthread
, you already know that it’s an RAII version of std::thread
and is safer to use in the sense that when a std::jthread
object with automatic storage duration goes out of scope, there is no need to call join
method because the destructor of std::jthread
calls the join
method . But that’s not the only thing the destructor does! It in fact sends a request to stop the execution of the task the std::jthread
object is tied to.
In this article I’ll explain how to use std::jthread
safely and prevent premature execution of the task and in the process show a simplified implementation of…