1/* Create threads from multiple threads in parallel.
2   Copyright 2007-2023 Free Software Foundation, Inc.
3
4   This file is part of GDB.
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 3 of the License, or
9   (at your option) any later version.
10
11   This program is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19#include <pthread.h>
20#include <stdio.h>
21#include <limits.h>
22
23#define NUM_CREATE 1
24#define NUM_THREAD 8
25
26void *
27thread_function (void *arg)
28{
29  int x = * (int *) arg;
30
31  printf ("Thread <%d> executing\n", x);
32
33  return NULL;
34}
35
36void *
37create_function (void *arg)
38{
39  pthread_attr_t attr;
40  pthread_t threads[NUM_THREAD];
41  int args[NUM_THREAD];
42  int i = * (int *) arg;
43  int j;
44
45  pthread_attr_init (&attr); /* set breakpoint 1 here.  */
46  pthread_attr_setstacksize (&attr, 2*PTHREAD_STACK_MIN);
47
48  /* Create a ton of quick-executing threads, then wait for them to
49     complete.  */
50  for (j = 0; j < NUM_THREAD; ++j)
51    {
52      args[j] = i * 1000 + j;
53      pthread_create (&threads[j], &attr, thread_function, &args[j]);
54    }
55
56  for (j = 0; j < NUM_THREAD; ++j)
57    pthread_join (threads[j], NULL);
58
59  pthread_attr_destroy (&attr);
60
61  return NULL;
62}
63
64int
65main (int argc, char **argv)
66{
67  pthread_attr_t attr;
68  pthread_t threads[NUM_CREATE];
69  int args[NUM_CREATE];
70  int n, i;
71
72  pthread_attr_init (&attr);
73  pthread_attr_setstacksize (&attr, 2*PTHREAD_STACK_MIN);
74
75  for (n = 0; n < 100; ++n)
76    {
77      for (i = 0; i < NUM_CREATE; i++)
78	{
79	  args[i] = i;
80	  pthread_create (&threads[i], &attr, create_function, &args[i]);
81	}
82
83      create_function (&i);
84      for (i = 0; i < NUM_CREATE; i++)
85	pthread_join (threads[i], NULL);
86    }
87
88  pthread_attr_destroy (&attr);
89
90  return 0;
91}
92