(CFLAGS-tst-align.c): Add -mpreferred-stack-boundary=4.
[glibc.git] / linuxthreads / Examples / ex10.c
blobf3ad51728367021169a82d3d91531d8d0edaff78
1 /* Tests for pthread_mutex_timedlock function.
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>
25 #include <time.h>
27 #define NUM_THREADS 10
28 #define NUM_ITERS 50
29 #define TIMEOUT_NS 100000000L
31 static void *thread (void *) __attribute__ ((__noreturn__));
32 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
34 int
35 main (void)
37 pthread_t th;
38 int i;
40 for (i = 0; i < NUM_THREADS; i++)
42 if (pthread_create (&th, NULL, thread, NULL) != 0)
43 error (EXIT_FAILURE, 0, "cannot create thread");
46 (void) thread (NULL);
47 /* notreached */
48 return 0;
52 static void *
53 thread (void *arg)
55 int i;
56 pthread_t self = pthread_self ();
57 static int linecount; /* protected by flockfile(stdout) */
59 for (i = 0; i < NUM_ITERS; i++)
61 struct timespec ts;
63 for (;;)
65 int err;
67 clock_gettime (CLOCK_REALTIME, &ts);
69 ts.tv_nsec += TIMEOUT_NS;
71 if (ts.tv_nsec >= 1000000000L) {
72 ts.tv_sec++;
73 ts.tv_nsec -= 1000000000L;
76 switch ((err = pthread_mutex_timedlock (&mutex, &ts)))
78 case 0:
79 flockfile (stdout);
80 printf ("%04d: thread %lu got mutex\n", ++linecount,
81 (unsigned long) self);
82 funlockfile (stdout);
83 break;
84 case ETIMEDOUT:
85 flockfile (stdout);
86 printf ("%04d: thread %lu timed out on mutex\n", ++linecount,
87 (unsigned long) self);
88 funlockfile (stdout);
89 continue;
90 default:
91 error (EXIT_FAILURE, err, "pthread_mutex_timedlock failure");
93 break;
96 ts.tv_sec = 0;
97 ts.tv_nsec = TIMEOUT_NS;
98 nanosleep (&ts, NULL);
100 flockfile (stdout);
101 printf ("%04d: thread %lu releasing mutex\n", ++linecount,
102 (unsigned long) self);
103 funlockfile (stdout);
104 pthread_mutex_unlock (&mutex);
107 pthread_exit (NULL);