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 <stdlib.h>
7#include <stdio.h>
8#include <pthread.h>
9
10
11static pthread_t s_thread[1000];
12static int       s_arg[1000];
13
14static void* thread_func(void* p)
15{
16  int thread_count = *(int*)(p);
17  if (thread_count > 0)
18  {
19    thread_count--;
20    // std::cout << "create " << thread_count << std::endl;
21    s_arg[thread_count] = thread_count;
22    pthread_create(&s_thread[thread_count], 0, thread_func,
23                   &s_arg[thread_count]);
24#if 0
25    std::cout << "created " << thread_count << "(" << s_thread[thread_count]
26              << ")" << std::endl;
27#endif
28  }
29  return 0;
30}
31
32int main(int argc, char** argv)
33{
34  unsigned thread_count;
35  int i;
36
37  thread_count = argc > 1 ? atoi(argv[1]) : 50;
38  assert(thread_count <= sizeof(s_thread) / sizeof(s_thread[0]));
39  assert(thread_count >= 1);
40  thread_count--;
41  // std::cout << "create " << thread_count << std::endl;
42  pthread_create(&s_thread[thread_count], 0, thread_func,
43                 &thread_count);
44#if 0
45  std::cout << "created " << thread_count << "(" << s_thread[thread_count]
46            << ")" << std::endl;
47#endif
48  for (i = thread_count; i >= 0; i--)
49  {
50    // std::cout << "join " << i << "(" << s_thread[i] << ")" << std::endl;
51    pthread_join(s_thread[i], 0);
52  }
53  return 0;
54}
55