Reputation: 1
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?
Upvotes: 0
Views: 538
Reputation: 6537
TBB provides thread class as a compatibility layer for C++03 which is as close to C++11 as possibly. Other libraries (e.g. 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");
}
Upvotes: 2