Skip to content

Instantly share code, notes, and snippets.

@rrichardson
Last active August 29, 2015 14:05
Show Gist options
  • Save rrichardson/076f504d6c7c495d9616 to your computer and use it in GitHub Desktop.
Save rrichardson/076f504d6c7c495d9616 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#define STACKSIZE (16 * 1024)
#define NUM_THREADS 100000
#define getlimit(x) getrlimit(RLIMIT_##x, &limit); printf("%s current: %lu, max: %lu\n", #x, limit.rlim_cur, limit.rlim_max);
void *do_nothing(void *args)
{
pthread_mutex_t* mtx = (pthread_mutex_t*) args;
pthread_mutex_lock(mtx);
pthread_mutex_unlock(mtx);
return NULL;
}
int main()
{
struct rlimit limit;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
pthread_mutex_t mtx;
int i = 0;
int err;
pthread_mutex_init(&mtx, NULL);
pthread_attr_init(&attr);
i = pthread_attr_setstacksize(&attr, STACKSIZE);
if (i != 0) {
fprintf(stderr, "Error setting stack size to %ul", STACKSIZE);
return 1;
}
pthread_mutex_lock(&mtx);
for (; i < NUM_THREADS; ++i)
{
if((err = pthread_create(&threads[i], &attr, do_nothing, (void*) &mtx))) {
fprintf(stderr, "Error creating thread: %d\n", err);
getlimit(NPROC);
getlimit(STACK);
return 1;
}
fprintf(stdout, "%d \n", i);
}
sleep(5);
pthread_mutex_unlock(&mtx);
if(pthread_join(threads[1], NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
printf("total threads: %d\n", i);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment