简体   繁体   English

在C ++中使用pthread_exit()是否安全?

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

pthread_exit() doesn't have the mechanism of stack unwinding. pthread_exit()没有堆栈展开机制。 Can we completely avoid using pthread_exit() in C++? 我们可以完全避免在C ++中使用pthread_exit()吗? Or, are there any cases where we require this API instead of return from thread function in C++? 或者,是否有任何我们需要此API而不是从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. 当首次调用main()的线程以外的线程从用于创建它的start例程返回时,会对pthread_exit()进行隐式调用。 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. pthread函数是特定于平台的。 C++ has its own platform-independent thread API. C ++有自己独立于平台的线程API。 It doesn't have a function that would correspond to pthread_exit . 它没有与pthread_exit对应的函数。 Use the std::thread API and don't worry about pthreads. 使用std :: thread API并不用担心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. 这将正确展开堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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