Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .