在 C++ 中使用 pthread_exit() 安全吗?
Is it safe to use pthread_exit() in C++?
pthread_exit()
没有堆栈展开的机制。我们可以完全避免在 C++ 中使用 pthread_exit()
吗?或者,在某些情况下,我们是否需要 C++ 中的线程函数使用此 API 而不是 return?
引用文档:
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.
这意味着你不需要自己调用它,除非你想避免从该函数返回(可能是裸函数,或中断处理程序或一些非常低级别的东西)。
pthread
函数是 platform-specific。 C++ 有自己的 platform-independent 线程 API。它没有对应于 pthread_exit
的函数。使用 std::thread API 不用担心 pthreads。
如果你需要在中间终止一个线程而不显式地一直返回到线程启动函数,抛出一个异常并在启动函数中捕获它。这将正确展开堆栈。
pthread_exit()
没有堆栈展开的机制。我们可以完全避免在 C++ 中使用 pthread_exit()
吗?或者,在某些情况下,我们是否需要 C++ 中的线程函数使用此 API 而不是 return?
引用文档:
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.
这意味着你不需要自己调用它,除非你想避免从该函数返回(可能是裸函数,或中断处理程序或一些非常低级别的东西)。
pthread
函数是 platform-specific。 C++ 有自己的 platform-independent 线程 API。它没有对应于 pthread_exit
的函数。使用 std::thread API 不用担心 pthreads。
如果你需要在中间终止一个线程而不显式地一直返回到线程启动函数,抛出一个异常并在启动函数中捕获它。这将正确展开堆栈。