views:

502

answers:

2

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

"The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process {PTHREAD_THREADS_MAX} would be exceeded."

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

So it means "the system lacked the necessary resources". My question is (and it may be a bit stupid) - what are these resources? Presumably it's a memory leak in my program (certainly possible, likely even), but I'd have thought that even so it could manage more than 300 considering the rest of the program does very little.

How can I find out how much memory my program has available to confirm that it's running out of it? There's plenty of memory and swap free so presumably there's an artificial limit imposed by the OS (Linux).

Thanks

A: 

Possibly a little overkill(?) but Valgrind can help you locate memleaks in Linux.

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

Daniel
+8  A: 

If you are not creating the thread with the attribute PTHREAD_CREATE_DETACHED (or detaching them with pthread_detach(), you may need to call pthread_join() on each created thread after it exits to free up the resources associated with it.

Miles
Thankyou! Just set that attribute and it's gone well past 4000 threads and counting. Many thanks - that's about 3 hours of frustration fixed :)
Ray2k