(CFLAGS-tst-align.c): Add -mpreferred-stack-boundary=4.
[glibc.git] / linuxthreads / Examples / ex9.c
blob3c8b8142e1d94e9517cd80758ce3754090d99cce
1 /* Tests for pthread_barrier_* functions.
2 Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc.
3 Contributed by Kaz Kylheku <kaz@ashi.footprints.net>, 2000.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
10 The GNU C Library 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 GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include <errno.h>
21 #include <error.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <pthread.h>
26 #define NUM_THREADS 10
27 #define NUM_ITERS 500
29 static void *thread (void *) __attribute__ ((__noreturn__));
30 static pthread_barrier_t barrier;
32 int
33 main (void)
35 pthread_t thread_list[NUM_THREADS];
36 int i;
38 if (pthread_barrier_init (&barrier, NULL, NUM_THREADS + 1) != 0)
39 error (EXIT_FAILURE, 0, "cannot initialize barrier");
41 for (i = 0; i < NUM_THREADS; i++)
43 if (pthread_create (&thread_list[i], NULL, thread, NULL) != 0)
44 error (EXIT_FAILURE, 0, "cannot create thread");
47 (void) thread (NULL);
49 for (i = 0; i < NUM_THREADS; i++)
51 pthread_join(thread_list[i], NULL);
54 return 0;
58 static void *
59 thread (void *arg)
61 int i;
62 pthread_t self = pthread_self ();
63 static pthread_t last_serial_thread;
64 static int linecount; /* protected by flockfile(stdout) */
66 for (i = 0; i < NUM_ITERS; i++)
68 switch (pthread_barrier_wait (&barrier))
70 case 0:
71 flockfile (stdout);
72 printf ("%04d: non-serial thread %lu\n", ++linecount,
73 (unsigned long) self);
74 funlockfile (stdout);
75 break;
76 case PTHREAD_BARRIER_SERIAL_THREAD:
77 flockfile (stdout);
78 printf ("%04d: serial thread %lu\n", ++linecount,
79 (unsigned long) self);
80 funlockfile (stdout);
81 last_serial_thread = self;
82 break;
83 default:
84 /* Huh? */
85 error (EXIT_FAILURE, 0, "unexpected return value from barrier wait");
89 if (pthread_equal (self, last_serial_thread))
91 flockfile (stdout);
92 printf ("%04d: last serial thread %lu terminating process\n",
93 ++linecount, (unsigned long) self);
94 funlockfile (stdout);
97 pthread_exit(NULL);