1 // Create threads in such a way that there is a realistic chance that the 2 // parent thread finishes before the created thread finishes. 3 4 5 #include <assert.h> 6 #include <limits.h> /* PTHREAD_STACK_MIN */ 7 #include <stdlib.h> 8 #include <stdio.h> 9 #include <pthread.h> 10 11 12 static pthread_t s_thread[1000]; 13 static int s_arg[1000]; 14 15 static void* thread_func(void* p) 16 { 17 int thread_count = *(int*)(p); 18 pthread_attr_t attr; 19 20 if (thread_count > 0) 21 { 22 thread_count--; 23 // std::cout << "create " << thread_count << std::endl; 24 s_arg[thread_count] = thread_count; 25 pthread_attr_init(&attr); 26 pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN); 27 pthread_create(&s_thread[thread_count], &attr, thread_func, 28 &s_arg[thread_count]); 29 pthread_attr_destroy(&attr); 30 #if 0 31 std::cout << "created " << thread_count << "(" << s_thread[thread_count] 32 << ")" << std::endl; 33 #endif 34 } 35 return 0; 36 } 37 38 int main(int argc, char** argv) 39 { 40 pthread_attr_t attr; 41 unsigned thread_count; 42 int i; 43 44 thread_count = argc > 1 ? atoi(argv[1]) : 50; 45 assert(thread_count <= sizeof(s_thread) / sizeof(s_thread[0])); 46 assert(thread_count >= 1); 47 thread_count--; 48 // std::cout << "create " << thread_count << std::endl; 49 pthread_attr_init(&attr); 50 pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN); 51 pthread_create(&s_thread[thread_count], &attr, thread_func, 52 &thread_count); 53 pthread_attr_destroy(&attr); 54 #if 0 55 std::cout << "created " << thread_count << "(" << s_thread[thread_count] 56 << ")" << std::endl; 57 #endif 58 for (i = thread_count; i >= 0; i--) 59 { 60 // std::cout << "join " << i << "(" << s_thread[i] << ")" << std::endl; 61 pthread_join(s_thread[i], 0); 62 } 63 return 0; 64 } 65