std::jthread introduced in C++20 is a new thread class that is cancellable and joinable. It is a wrapper around std::thread that provides a few additional features. In this post, I wanted to talk about std::jthread and how it can be used in modern C++ codebases.

Advantages over C++11 std::thread:

  • cancellable, can be stopped at any time, unlike std::thread which can only be stopped at the end of the thread function
  • works better with RAII pattern, since it can be joined or detached in the destructor

Cancellation mechanism with request_stop

First, let’s see how to use the std::jthread with its stop token mechanism:


#include <iostream>
#include <thread>
#include <stop_token>

void foo(std::stop_token stoken) {
    while (!stoken.stop_requested()) {
        std::cout << "Running\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main() {
    std::jthread t(foo);
    std::this_thread::sleep_for(std::chrono::seconds(5));
    t.request_stop();
    t.join();
    return 0;
}

As expected, this prints

Running
Running
Running
Running
Running

...Program finished with exit code 0
Press ENTER to exit console.

the token is implicitly passed to the thread function and can be used to check if the thread should stop. The request_stop method is used to signal the thread to stop. While this can be done in application code with custom flags, std::jthread provides a standard way to do this.

RAII pattern

std::jthread works well with RAII pattern. It can be joined or detached in the destructor. This means you don’t have to worry about forgetting to join a thread. Here’s an example:


#include <iostream>
#include <thread>
#include <stop_token>

void foo(std::stop_token stoken) {
    while (!stoken.stop_requested()) {
        std::cout << "Running\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout << "Thread stopped\n";
}

int main() {
    {
        std::jthread t(foo);
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
    return 0;
}

Note the above example code, thread stop is implicitly done as soon as the parent block goes out of scope.

This will print

Running
Running
Running
Running
Running
Thread stopped

Conclusion

std::jthread is a new thread class introduced in C++20 that provides a few additional features over std::thread. It is cancellable and joinable, and works well with RAII pattern. It is a good choice for modern C++ codebases that need to work with threads.