Why does pthread_create () end with only 2 threads active?

I am having problems with the first run into threads in C. I'm trying (now) to write a very simple server program that accepts a socket connection and starts a new thread to handle it. It seems to work fine except that it will create about 300 threads (303, sometimes 304) before pthread_create () exits with the EAGAIN code, which means:

"The system did not have the necessary resources to create another thread, or the system limit imposed on the total number of threads in the {PTHREAD_THREADS_MAX} process will be exceeded.

This is not 303 threads at the same time - each thread exits, which is confirmed by gdb. Each time a process request function is called, two threads are executed.

This means that the system does not have enough resources. My question (and it might be a little silly) is what are these resources? Presumably, this is a memory leak in my program (of course, perhaps even very probable), but I would have thought that even so that it could manage more than 300, given that the rest of the program is very small.

How do I know how much memory my program has available to confirm that it is running out? There is a lot of memory and swap for free, so presumably there is an artificial limit imposed by the OS (Linux).

thanks

+6
c multithreading pthreads
source share
2 answers

If you are not creating a thread with the PTHREAD_CREATE_DETACHED attribute (or separating them with pthread_detach() , you may need to call pthread_join() for each thread you create after exiting to free the resources associated with it.

+10
source share

Maybe a little overkill (?), But Valgrind can help you find memleaks on Linux.

Could you post some code snippets? Preferably, the parts where you allocate / free memory / sockets and where you create your threads.

0
source share

All Articles