Sunday, February 4, 2024

jthread in C++ 20 concurrency - a wrapper around std::thread...

jthread is a new entrant in C++ 20. It's a simple wrapper around std::thread which is based upon RAII objective - that is resource acquisition is resource initialization.

The j in the jthread stands for automatic joining.

This means that there is no need to call join on the newly created thread object - the program won't terminate abnormally.

When a jthread object goes out of scope or is otherwise destroyed, it automatically calls join() to ensure the thread completes before the object is destroyed. This prevents potential resource leaks or undefined behavior that could occur with std::thread.

The other aspect of jthread is the cooperative interruption.

We will discuss it in the next post.

No comments: