Overview of Cooperative Interruption Thread
Explore how cooperative interruption threads work in C++20 by using std::stop_token, std::stop_callback, and std::stop_source. Understand why forcibly killing threads is unsafe and how to properly signal and handle stop requests. This lesson helps you manage thread interruptions safely and learn about automatic joining with std::jthread.
We'll cover the following...
We'll cover the following...
The additional functionality of the cooperative interruption thread is based on the std::stop_token, the std::stop_callback, and the std::stop_source commands.
First, why is it not a good idea to kill a thread?
...⚠️ Killing a thread is dangerous
Killing a thread is dangerous because you don’t know the state of the thread. Here are two possible malicious outcomes.
- The thread is only half-done with its job. Consequently, you don’t know the state of its job and, hence, the state of your program. You end with
, and all bets are off. undefined behavior All bets are open. Your program can produce the correct result, the wrong result, crashes during run-time, or may not even compile. That behavior might change when porting to a new platform, upgrading to a new compiler or as a result of an unrelated code change. - The thread may be in a critical section and have locked a mutex. Killing a thread while it locks a mutex ends with a high probability in a
. deadlock A deadlock is a state in which at least one thread is blocked forever because it waits for the release of a resource, it does never get. There are two main reasons for deadlocks: a mutex has not been unlocked or you lock your mutexes in a different order.