我见过的有关多线程的所有示例都在 main
方法中使用此方法来等待线程完成:
pthread_join(thread_id, NULL);
但是如果我不想让它等待怎么办?我希望我的 main 函数在线程执行工作时继续,但同时,我不希望 main 在线程存在之前退出。这在 C/C++ 中可能吗?
最佳答案
如果您想避免使用pthread_join()
,则可以选择pthread_detach()
。
来自 man-page :
int pthread_detach(pthread_t thread);
The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are
automatically released back to the system without the need for
another thread to join with the terminated thread.it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).
关于c - C/C++ 中的多线程无需等待线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860143/