1 /* C11 threads timed mutex tests.
2 Copyright (C) 2018 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
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.
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; if not, see
17 <http://www.gnu.org/licenses/>. */
23 #include <support/check.h>
25 /* Shared mutex between child and parent. */
28 /* Shared counter to check possible race conditions. */
29 static char shrd_counter
;
31 /* Maximum amount of time waiting for mutex. */
32 static struct timespec wait_time
;
34 /* Function to choose an action to do, depending on mtx_timedlock
37 choose_action (int action
, char* thread_name
)
44 if (mtx_unlock (&mutex
) != thrd_success
)
45 FAIL_EXIT1 ("mtx_unlock failed");
52 FAIL_EXIT1 ("%s lock error", thread_name
);
60 char child_name
[] = "child";
62 /* Try to lock mutex. */
63 choose_action (mtx_timedlock (&mutex
, &wait_time
), child_name
);
64 thrd_exit (thrd_success
);
71 char parent_name
[] = "parent";
73 if (mtx_init (&mutex
, mtx_timed
) != thrd_success
)
74 FAIL_EXIT1 ("mtx_init failed");
76 if (clock_gettime (CLOCK_REALTIME
, &wait_time
) != 0)
77 FAIL_EXIT1 ("clock_gettime failed");
78 /* Tiny amount of time, to assure that if any thread finds it busy.
79 It will receive thrd_timedout. */
80 wait_time
.tv_nsec
+= 1;
81 if (wait_time
.tv_nsec
== 1000 * 1000 * 1000)
83 wait_time
.tv_sec
+= 1;
84 wait_time
.tv_nsec
= 0;
87 if (thrd_create (&id
, child_add
, NULL
) != thrd_success
)
88 FAIL_EXIT1 ("thrd_create failed");
90 choose_action (mtx_timedlock (&mutex
, &wait_time
), parent_name
);
92 if (thrd_join (id
, NULL
) != thrd_success
)
93 FAIL_EXIT1 ("thrd_join failed");
95 if (shrd_counter
!= 2 && shrd_counter
!= 1)
96 FAIL_EXIT1 ("shrd_counter != {1,2} (%d)", shrd_counter
);
103 #include <support/test-driver.c>