How do I terminate a thread in C++11?

后端 未结 5 2331
长发绾君心
长发绾君心 2020-11-22 09:42

I don\'t need to terminate the thread correctly, or make it respond to a \"terminate\" command. I am interested in terminating the thread forcefully using pure C++11.

5条回答
  •  面向向阳花
    2020-11-22 10:38

    Tips of using OS-dependent function to terminate C++ thread:

    1. 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.

    2. 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 .

提交回复
热议问题