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 mechanisms as to how the stop_token can be signaled to stop may vary and can be grouped broadly into two categories:

  1. by relying on jthread‘s internal shared stop-state .
  2. by employing an external shared stop-state .

In this article, I’ll explain how to cooperatively signal a stop/cancellation to an executing jthread by relying on jthread‘s internal shared stop-state and making use of jthread::request_stop or jthread::~jthread (or jthread‘s destructor). Therefore in this article I’ll not explain about std::stop_source since it will be managed internally by jthread .

2. Using std::jthread internal stop-state

First line of the second paragraph of cpp reference page says the following about jthread ‘s internal stop-state:

jthread logically holds an internal private member of type stop_source, which maintains a…

Gajendra Gulgulia

I'm a backend software developer and modern C++ junkie. I run a modern cpp youtube channel (https://www.youtube.com/@masteringmoderncppfeatures6302/videos)