xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/testsuite/gdb.threads/fork-thread-pending.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /* This testcase is part of GDB, the GNU debugger.
2 
3    Copyright 2008-2016 Free Software Foundation, Inc.
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17 
18 #include <pthread.h>
19 #include <assert.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 
28 #define NUMTHREADS 10
29 
30 volatile int done = 0;
31 static pthread_barrier_t barrier;
32 
33 static void *
34 start (void *arg)
35 {
36   while (!done)
37     usleep (100);
38   assert (0);
39   return arg;
40 }
41 
42 void *
43 thread_function (void *arg)
44 {
45   int x = * (int *) arg;
46 
47   printf ("Thread <%d> executing\n", x);
48 
49   pthread_barrier_wait (&barrier);
50 
51   while (!done)
52     usleep (100);
53 
54   return NULL;
55 }
56 
57 void *
58 thread_forker (void *arg)
59 {
60   int x = * (int *) arg;
61   pid_t pid;
62   int rv;
63   int i;
64   pthread_t thread;
65 
66   printf ("Thread forker <%d> executing\n", x);
67 
68   pthread_barrier_wait (&barrier);
69 
70   switch ((pid = fork ()))
71     {
72     case -1:
73       assert (0);
74     default:
75       wait (&rv);
76       done = 1;
77       break;
78     case 0:
79       i = pthread_create (&thread, NULL, start, NULL);
80       assert (i == 0);
81       i = pthread_join (thread, NULL);
82       assert (i == 0);
83 
84       assert (0);
85     }
86 
87   return NULL;
88 }
89 
90 int
91 main (void)
92 {
93   pthread_t threads[NUMTHREADS];
94   int args[NUMTHREADS];
95   int i, j;
96 
97   alarm (600);
98 
99   i = pthread_barrier_init (&barrier, NULL, NUMTHREADS);
100   assert (i == 0);
101 
102   /* Create a few threads that do mostly nothing, and then one that
103      forks.  */
104   for (j = 0; j < NUMTHREADS - 1; ++j)
105     {
106       args[j] = j;
107       pthread_create (&threads[j], NULL, thread_function, &args[j]);
108     }
109 
110   args[j] = j;
111   pthread_create (&threads[j], NULL, thread_forker, &args[j]);
112 
113   for (j = 0; j < NUMTHREADS; ++j)
114     {
115       pthread_join (threads[j], NULL);
116     }
117 
118   return 0;
119 }
120