简体   繁体   中英

Is it safe to use pthread_exit() in C++?

pthread_exit() doesn't have the mechanism of stack unwinding. Can we completely avoid using pthread_exit() in C++? Or, are there any cases where we require this API instead of return from thread function in C++?

To quote from the documentation:

An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status.

Which means that you don't need to call it yourself unless you want to avoid returning from that function (perhaps naked functions, or interrupt handlers or something really low level).

pthread functions are platform-specific. C++ has its own platform-independent thread API. It doesn't have a function that would correspond to pthread_exit . Use the std::thread API and don't worry about pthreads.

If you need to terminate a thread in the middle without explicitly returning all the way up to the thread starting function, throw an exception and catch it in the starting function. This will unwind the stack properly.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM