Thread termination and cancellation mechanisms in C include: Thread termination: std::thread::join() blocks the current thread until the target thread completes execution; std::thread::detach() detaches the target thread from thread management. Thread cancellation: std::thread::request_termination() requests the target thread to terminate execution; std::thread::get_id() obtains the target thread ID and can be used with std::terminate() to immediately terminate the target thread. In practice, request_termination() allows the thread to decide the timing of termination, and join() ensures that the worker thread completes execution before the main thread exits. Note that thread cancellation is not always respected, and terminating a thread may lead to undefined behavior.
#C Concurrent Programming: How to perform thread termination and cancellation?
In multi-threaded applications, thread termination and cancellation are critical operations when a specific thread or its task is no longer needed. C provides multiple mechanisms to implement thread termination and cancellation:
Thread termination
: Block the current thread until the target thread completes execution.
: Detach the target thread from thread management. The thread will continue executing but can no longer be accessed through its
std::thread object.
Thread cancellation
std::terminate()
function. This immediately terminates the target thread.
Consider an example where two threads are created: the main thread and the worker thread. The worker thread executes an infinite loop while the main thread waits for user input and then terminates the worker thread:
#include <iostream> #include <thread> void work_thread() { while (true) { // 无限循环 } } int main() { std::thread worker(work_thread); std::cout << "按回车键终止工作线程:" << std::endl; std::cin.get(); worker.request_termination(); worker.join(); return 0; }
##request_termination()
join()
Thread cancellation is not always respected, especially if the thread performs a critical section or other uninterruptible operation.
The above is the detailed content of C++ Concurrent Programming: How to do thread termination and cancellation?. For more information, please follow other related articles on the PHP Chinese website!