C++20 Concurrency: part-3 request_stop and stop_token for std::jthread

Gajendra Gulgulia
7 min readJan 12, 2022

In this article, we explore the latest feature of C++20’s std::jthreadthat allows one to signal a stop or cancellation to an already executing thread in certain situation. Quoting the first line again from cpp reference:

the class jthread represents a single thread of execution … , and can be cancelled/stopped in certain situations.

To keep my article readable, I’ll omit std:: and all occurrences of library constructs imply that they belong to C++’s std namespace unless explicitly stated otherwise.

1. Introduction: Two ways to cooperatively stop the thread

jthread provides a cooperative means to stop a thread of execution which implies that the threads cannot be interrupted¹ or killed² but can only be signaled to stop. There are two ways to cooperatively stop the thread and both the methods make use of a shared stop-state of type std::stop_source.

With the help of shared stop-state ( stop_source ) and a std::stop_token a check can be performed whether or not a stop request has been made. If it has been made, then the method that the thread executes can return immediately, and the responsibility to provide the implementation to return on a stop request falls on the programmer. But the…

--

--