pthread_create() fails after 382 threads

Hi,

I have a multi-thread problem illustrated by the following snippet.

My app is a server that listens on a socket, accepts connections and
fires off a thread to service the connection. The threads all terminate
ok but pthread_create() fails with errno = EAGAIN after several hundred
connections have been serviced.

It would appear to be a per process limit as the following code can be
run concurrently and both processes stop at t = 382.

/proc/sys/kernel/threads-max is 52467. (Per process thread limit is 26233).

Mandriva 2010.2
libpthread 2.11.1
libc 2.11.1

Would appreciate anyone running the following on their Linux.

Thanks,

Jan


// Link with -lpthread
//
int t;

static void * thread(void * arg)
{
printf("Thread %i\n", t);
return 0;
}

int main()
{
pthread_t thid;
struct rlimit r;

// RLIMIT_NPROC = max threads per process (returns 26233).
//
getrlimit(RLIMIT_NPROC, &r);

for(t = 0; t < 2000; t++)
{
if(pthread_create(&thid, 0, &thread, 0))
{
// Get here on t = 382 with errno = EAGAIN
// (Resource temporarily unavailable).
printf("%i (%s)\n", errno, strerror(errno));
break;
}
}

return 0;
}
Doh! Fixed it.

pthread_detach(thid);

Too long with MS I guess, where threads are detached by default.

Apologies.

Jan

My app is a server that listens on a socket, accepts connections and
fires off a thread to service the connection


It is fine for learning purposes, but it is also a very inefficient way of handling connections.
Topic archived. No new replies allowed.