Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 1 Feb 2004 11:50:12 -0500 (EST)
From:      Daniel Eischen <eischen@vigrid.com>
To:        Craig Rodrigues <rodrigc@crodrigues.org>
Cc:        freebsd-threads@freebsd.org
Subject:   Re: pthread_create() blocks if maxthreads reached?
Message-ID:  <Pine.GSO.4.10.10402011132590.524-100000@pcnet5.pcnet.com>
In-Reply-To: <20040201152105.GA2370@crodrigues.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sun, 1 Feb 2004, Craig Rodrigues wrote:

> On Sat, Jan 31, 2004 at 11:27:39PM -0800, Julian Elischer wrote:
> > > 
> > > If I link with -lpthread, the program seems to
> > > block in the pthread_create() call, instead of
> > > returning EAGAIN (to indicate that a new thread cannot
> > > be created due to hitting some system limit). 
> > 
> > is that what you expected?
> 
> 
> No that is not what I expected.  I expected
> that pthread_create() should either:
>    - if it creates the thread successfully, return 0
>    - if it cannot create the thread, return EAGAIN
>      if a resource limit is it, or EINVAL if bad parameters
>      were passed down into the pthread_create() call 
> 
> 
> I never expected that pthread_create() would block.

You're missing the point.  pthread_create() doesn't block;
you're application blocks because it has consumed the limit
of kernel threads allowed.  It just so happens that the
only runnable thread is making a lot of calls to
pthread_create(), but it could be doing anything and
it would still block.

#include <err.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


static pthread_mutex_t sync_lock;

static void *
worker(void *arg)
{
	pthread_mutex_lock(&sync_lock);
	pthread_mutex_unlock(&sync_lock);
	select(0, NULL, NULL, NULL, NULL);
	return (NULL);
}


int
main(int argc, char** argv)
{
	pthread_t *threads;
	int i, n;
	
	if (argc > 1) {
		n = strtoimax(argv[1], NULL, 10);
		printf("Using %d threads (parameter)\n", n);
	} else {
		n = 5;
		printf("Using %d threads (default)\n", n);
	}

	threads = (pthread_t *)malloc(sizeof(pthread_t) * n);

	pthread_mutex_init(&sync_lock, NULL);
	pthread_mutex_lock(&sync_lock);

	/* Create and start n threads. */
	for (i = 0; i < n; i++) {
		if (pthread_create(&threads[i], NULL, worker, NULL) != 0) {
			err(1, NULL);
		}
	}
	/* Let the threads loose. */
	printf("Created %d threads; letting them loose.\n", i);
	pthread_mutex_unlock(&sync_lock);

	sleep(10);
	printf("Main thread waking up after sleeping\n");

	/* Join the threads. */
	for (i = 0; i < n; i++) {
		if (pthread_join(threads[i], NULL) != 0) {
			err(1, NULL);
		}
		printf("Joined thread %d\n", i);
	}

	free(threads);
	return (0);
}



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.GSO.4.10.10402011132590.524-100000>