使用 pthread 时遇到的资源不足的问题

项目里遇到了一个 pthread_create 调用失败、返回资源不足的问题。

走读了代码,发现代码里反复调用了 pthread_create 创建了很多短任务;但主线程里并没有等待,而是任由其运行到退出。

查阅了 pthread 手册,对于新创建的 thread,它必须被 join 或者被 detach,这样才能避免 thread 相关的内部数据结构的泄漏。

$ man 3 pthread_create

A thread may either be joinable or detached... When a detached thread terminates, its resources are automatically released back to the system: it is not possible to join with the thread in order to obtain its exit status. Making a thread detached is useful for some types of daemon threads whose exit status the application does not need to care about...

针对项目实际情况,因为不需要 join,所以在调用 pthread_create 创建线程之后,添加了 pthread_detach 的调用,解决资源泄漏的问题。

Read More: