本文介绍了创建多个线程后,Pthread_create失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个处理客户端连接的应用程序。我将为每个请求生成一个线程,因为任务很短。但是,在处理一定数量的连接后,我仍然遇到问题。具体来说,在381个连接之后,pthread_create无法创建新线程。我知道如果应用程序资源不足,或者已经创建了多个PTHREAD_THREADS_MAX线程,这可能会失败。

I'm developing an application which handles client connections. I'm spawning a thread for each request, since there will be short tasks. However, I keep having a problem after handling a certain amount of connections. Specifically, after 381 connections, pthread_create fails to create a new thread. I know this can fail if the application runs out of resources, or more than PTHREAD_THREADS_MAX threads have been already created.

奇怪的是,当381个线程已经停止时,发生此错误。我不是在使用pthread_join等待这些线程停止运行,我相信pthreads不需要我以某种方式停止线程,如果我做错了,请纠正我(至少联机帮助页中没有提及)。我以为可能是在同时生成多个线程时产生的,但是,我已经对其进行了多次测试,并且每次第382个线程创建失败时。

The strange thing is the first 381 threads have already stopped when this error occurs. I'm not using pthread_join to wait for these threads to stop, I believe pthreads don't require me to somehow "stop" the thread, correct me if i'm wrong(at least the manpage does not mention this). I thought maybe this could be produced when several threads were spawn at the same time, however, I've tested it several times and every time the 382th thread creation fails.

有人知道会发生什么吗?任何帮助将不胜感激。

Does anyone know what could be happening? Any help will be appreciated.

提前感谢。

推荐答案

如果您不调用 pthread_join 或分离线程(通过调用 pthread_detach 或使用属性以分离状态创建它),终止线程使用的资源将永远不会被释放。这是你的问题。如果不需要加入线程,请在创建线程后立即将其分离。

If you do not call pthread_join or detach the thread (either by calling pthread_detach or creating it in the detached state using attributes), the resources used by the terminated thread will never be freed. This is your problem. If you don't need to join your threads, detach them as soon as you create them.

这篇关于创建多个线程后,Pthread_create失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 08:02