Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would pthread_create() fail with only 2 threads active?

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

like image 434
Ray2k Avatar asked Mar 08 '09 02:03

Ray2k


People also ask

What causes pthread_create to fail?

The pthread_create() function will fail if: [EAGAIN] 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.

How many threads does pthread_create create?

The pthread_create() function can only create one thread. You may call it multiple times -- apparently 825 without error.

How many arguments can be passed to pthread_create?

The pthread_create() routine permits the programmer to pass one argument to the thread start routine.

Which value does pthread_create () function return if it is successfully executed?

On success, pthread_create() returns 0; on error, it returns an error number, and the contents of *thread are undefined. That value simply indicates whether the thread creation was successful or not.


1 Answers

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.

like image 78
Miles Avatar answered Oct 14 '22 18:10

Miles