While using C++11 thread model or TBB thread class, how can I cancel other thread (If you are using pthread lib, you could cancel other thread using pthread_cancel)? Ps: is there the conception of thread cancellation point as pthread in C++11 thread model or tbb thread class?
TBB provides thread class as a compatibility layer for C++03 which is as close to C++11 as possibly. Other libraries (eg boost ) also provide a thread class which doesn't have a cancel()
method.
Thus the question is rather "how to cancel a thread in C++". And the answer is: there is no built-in cancellation, just interrupt politely .
pthread_cancel
is a bad idea for general C++ program since it does not respect objects lifetime.
Write your own cancellation point which reads a cancellation flag and if it is set, throws an exception to unwind the stack correctly.
std::atomic<bool> is_cancelled;
void check_cancel() {
if(is_cancelled)
throw std::runtime_error("cancelled");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.