1/* Test that pthread_mutex_timedlock properly times out.
2 Copyright (C) 2016-2024 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
25pthread_mutex_t mutex;
26
27static void *
28thr (void *arg)
29{
30 struct timespec abstime;
31 clock_gettime (CLOCK_REALTIME, tp: &abstime);
32 abstime.tv_sec += 1;
33 int ret = pthread_mutex_timedlock (mutex: &mutex, abstime: &abstime);
34 if (ret == 0)
35 {
36 puts (s: "mutex_timedlock didn't fail");
37 exit (1);
38 }
39 if (ret != ETIMEDOUT)
40 {
41 printf (format: "mutex_timedlock failed: %s\n", strerror (errnum: ret));
42 exit (1);
43 }
44
45 return 0;
46}
47
48static int
49do_test (void)
50{
51 pthread_t pt;
52 pthread_mutexattr_t ma;
53
54 if (pthread_mutexattr_init (attr: &ma) != 0)
55 {
56 puts (s: "mutexattr_init failed");
57 return 0;
58 }
59 if (pthread_mutexattr_setrobust (attr: &ma, robustness: PTHREAD_MUTEX_ROBUST_NP) != 0)
60 {
61 puts (s: "mutexattr_setrobust failed");
62 return 1;
63 }
64 if (pthread_mutex_init (mutex: &mutex, mutexattr: &ma))
65 {
66 puts (s: "mutex_init failed");
67 return 1;
68 }
69
70 if (pthread_mutexattr_destroy (attr: &ma))
71 {
72 puts (s: "mutexattr_destroy failed");
73 return 1;
74 }
75
76 if (pthread_mutex_lock (mutex: &mutex))
77 {
78 puts (s: "mutex_lock failed");
79 return 1;
80 }
81
82 if (pthread_create (newthread: &pt, NULL, start_routine: thr, NULL))
83 {
84 puts (s: "pthread_create failed");
85 return 1;
86 }
87
88 if (pthread_join (th: pt, NULL))
89 {
90 puts (s: "pthread_join failed");
91 return 1;
92 }
93
94 if (pthread_mutex_unlock (mutex: &mutex))
95 {
96 puts (s: "mutex_unlock failed");
97 return 1;
98 }
99
100 if (pthread_mutex_destroy (mutex: &mutex))
101 {
102 puts (s: "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

source code of glibc/sysdeps/pthread/tst-robust10.c