| 1 |
#define _GNU_SOURCE /* For pthread_getattr_np */ |
| 2 |
#include <pthread.h> |
| 3 |
#include <unistd.h> |
| 4 |
#include <stdio.h> |
| 5 |
#include <assert.h> |
| 6 |
#include <errno.h> |
| 7 |
#include <stdlib.h> |
| 8 |
|
| 9 |
static pthread_once_t printed_p = PTHREAD_ONCE_INIT; |
| 10 |
void print_it () |
| 11 |
{ |
| 12 |
int rc; |
| 13 |
pthread_attr_t foo; |
| 14 |
size_t size; |
| 15 |
rc = pthread_getattr_np (pthread_self(), & foo); |
| 16 |
assert (rc == 0); |
| 17 |
rc = pthread_attr_getstacksize(&foo, &size); |
| 18 |
assert (rc == 0); |
| 19 |
printf ("stacksize=%u\n", size); |
| 20 |
rc = pthread_attr_destroy (&foo); |
| 21 |
assert (rc == 0); |
| 22 |
} |
| 23 |
|
| 24 |
void *tfunc(void *arg) |
| 25 |
{ |
| 26 |
/* Choose some random thread to print stack size */ |
| 27 |
(void) pthread_once(&printed_p, &print_it); |
| 28 |
return NULL; |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
#define MAXTHREADS 4096 |
| 33 |
|
| 34 |
int |
| 35 |
main(int argc, char **argv) |
| 36 |
{ |
| 37 |
pthread_t thr[MAXTHREADS]; |
| 38 |
pthread_attr_t attr; |
| 39 |
int numthreads; |
| 40 |
int stacksize; |
| 41 |
int rc; |
| 42 |
int threads_created = 0; |
| 43 |
size_t i; |
| 44 |
|
| 45 |
if (argc != 3) { |
| 46 |
fprintf(stderr, "Usage: %s numthreads stacksize|0\n", argv[0]); |
| 47 |
return -1; |
| 48 |
} |
| 49 |
|
| 50 |
numthreads = atoi(argv[1]); |
| 51 |
if (numthreads > MAXTHREADS) { |
| 52 |
numthreads = MAXTHREADS; |
| 53 |
} |
| 54 |
stacksize = atoi(argv[2]); |
| 55 |
|
| 56 |
rc = pthread_attr_init(&attr); |
| 57 |
assert (rc == 0); |
| 58 |
|
| 59 |
if (stacksize > 0) { |
| 60 |
rc = pthread_attr_setstacksize(&attr, (size_t) stacksize); |
| 61 |
assert (rc == 0); |
| 62 |
} |
| 63 |
|
| 64 |
for (i = 0; i < numthreads; i++) { |
| 65 |
rc = pthread_create(&thr[i], (stacksize == 0 ? NULL : &attr), tfunc, NULL); |
| 66 |
|
| 67 |
/* On systems with not enough memory, pthread_create() can fail |
| 68 |
* after creating lots of threads. Just ignore this error (if |
| 69 |
* we've already created at least 100 threads). */ |
| 70 |
if (rc == EAGAIN && threads_created > 100) |
| 71 |
break; |
| 72 |
assert (rc == 0); |
| 73 |
threads_created++; |
| 74 |
} |
| 75 |
|
| 76 |
/* Wait for all the threads to finish (otherwise we can exit |
| 77 |
* before one of our threads has the chance to print the stack |
| 78 |
* size). */ |
| 79 |
for (i = 0; i < threads_created; i++) { |
| 80 |
pthread_join(thr[i], NULL); |
| 81 |
} |
| 82 |
|
| 83 |
rc = pthread_attr_destroy(&attr); |
| 84 |
assert (rc == 0); |
| 85 |
|
| 86 |
return 0; |
| 87 |
} |
| 88 |
|