(res_isourserver): Fix cast.
[glibc/pb-stable.git] / linuxthreads / Examples / ex10.c
blobd89f4f469d698ea49a68c49d61e2e6d4d11a2365
1 /* Tests for pthread_mutex_timedlock function.
2 Copyright (C) 2000 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 Library General Public License as
7 published by the Free Software Foundation; either version 2 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 Library General Public License for more details.
15 You should have received a copy of the GNU Library 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 *);
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 (;;)
66 clock_gettime (CLOCK_REALTIME, &ts);
68 ts.tv_nsec += TIMEOUT_NS;
70 if (ts.tv_nsec > 1000000000L) {
71 ts.tv_sec++;
72 ts.tv_nsec -= 1000000000L;
75 switch (pthread_mutex_timedlock (&mutex, &ts))
77 case 0:
78 flockfile (stdout);
79 printf ("%04d: thread %lu got mutex\n", ++linecount,
80 (unsigned long) self);
81 funlockfile (stdout);
82 break;
83 case ETIMEDOUT:
84 flockfile (stdout);
85 printf ("%04d: thread %lu timed out on mutex\n", ++linecount,
86 (unsigned long) self);
87 funlockfile (stdout);
88 continue;
90 break;
93 ts.tv_sec = 0;
94 ts.tv_nsec = TIMEOUT_NS;
95 nanosleep (&ts, NULL);
97 flockfile (stdout);
98 printf ("%04d: thread %lu releasing mutex\n", ++linecount,
99 (unsigned long) self);
100 funlockfile (stdout);
101 pthread_mutex_unlock (&mutex);
104 pthread_exit (NULL);