1 /* Test that pthread_mutex_timedlock properly times out.
2 Copyright (C) 2016-2022 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
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
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
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.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19 #include <pthread.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24
25 pthread_mutex_t mutex;
26
27 static void *
thr(void * arg)28 thr (void *arg)
29 {
30 struct timespec abstime;
31 clock_gettime (CLOCK_REALTIME, &abstime);
32 abstime.tv_sec += 1;
33 int ret = pthread_mutex_timedlock (&mutex, &abstime);
34 if (ret == 0)
35 {
36 puts ("mutex_timedlock didn't fail");
37 exit (1);
38 }
39 if (ret != ETIMEDOUT)
40 {
41 printf ("mutex_timedlock failed: %s\n", strerror (ret));
42 exit (1);
43 }
44
45 return 0;
46 }
47
48 static int
do_test(void)49 do_test (void)
50 {
51 pthread_t pt;
52 pthread_mutexattr_t ma;
53
54 if (pthread_mutexattr_init (&ma) != 0)
55 {
56 puts ("mutexattr_init failed");
57 return 0;
58 }
59 if (pthread_mutexattr_setrobust (&ma, PTHREAD_MUTEX_ROBUST_NP) != 0)
60 {
61 puts ("mutexattr_setrobust failed");
62 return 1;
63 }
64 if (pthread_mutex_init (&mutex, &ma))
65 {
66 puts ("mutex_init failed");
67 return 1;
68 }
69
70 if (pthread_mutexattr_destroy (&ma))
71 {
72 puts ("mutexattr_destroy failed");
73 return 1;
74 }
75
76 if (pthread_mutex_lock (&mutex))
77 {
78 puts ("mutex_lock failed");
79 return 1;
80 }
81
82 if (pthread_create (&pt, NULL, thr, NULL))
83 {
84 puts ("pthread_create failed");
85 return 1;
86 }
87
88 if (pthread_join (pt, NULL))
89 {
90 puts ("pthread_join failed");
91 return 1;
92 }
93
94 if (pthread_mutex_unlock (&mutex))
95 {
96 puts ("mutex_unlock failed");
97 return 1;
98 }
99
100 if (pthread_mutex_destroy (&mutex))
101 {
102 puts ("mutex_destroy failed");
103 return 1;
104 }
105
106 return 0;
107 }
108
109 #define TEST_FUNCTION do_test ()
110 #include "../test-skeleton.c"
111