malloc-h: New module.
[gnulib.git] / lib / pthread_mutex_timedlock.c
blob2e13e26e825c4cd522f4e2282e78d5a27aee1829
1 /* Lock a mutex, abandoning after a certain time.
2 Copyright (C) 2019-2020 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 #include <config.h>
19 /* Specification. */
20 #include <pthread.h>
22 #include <errno.h>
23 #include <limits.h>
24 #include <sys/time.h>
25 #include <time.h>
27 int
28 pthread_mutex_timedlock (pthread_mutex_t *mutex, const struct timespec *abstime)
30 /* Poll the mutex's state in regular intervals. Ugh. */
31 /* POSIX says:
32 "Under no circumstance shall the function fail with a timeout if
33 the mutex can be locked immediately. The validity of the abstime
34 parameter need not be checked if the mutex can be locked
35 immediately."
36 Therefore start the loop with a pthread_mutex_trylock call. */
37 for (;;)
39 int err;
40 struct timeval currtime;
41 unsigned long remaining;
42 struct timespec duration;
44 err = pthread_mutex_trylock (mutex);
45 if (err != EBUSY)
46 return err;
48 gettimeofday (&currtime, NULL);
50 if (currtime.tv_sec > abstime->tv_sec)
51 remaining = 0;
52 else
54 unsigned long seconds = abstime->tv_sec - currtime.tv_sec;
55 remaining = seconds * 1000000000;
56 if (remaining / 1000000000 != seconds) /* overflow? */
57 remaining = ULONG_MAX;
58 else
60 long nanoseconds =
61 abstime->tv_nsec - currtime.tv_usec * 1000;
62 if (nanoseconds >= 0)
64 remaining += nanoseconds;
65 if (remaining < nanoseconds) /* overflow? */
66 remaining = ULONG_MAX;
68 else
70 if (remaining >= - nanoseconds)
71 remaining -= (- nanoseconds);
72 else
73 remaining = 0;
77 if (remaining == 0)
78 return ETIMEDOUT;
80 /* Sleep 1 ms. */
81 duration.tv_sec = 0;
82 duration.tv_nsec = 1000000;
83 if (duration.tv_nsec > remaining)
84 duration.tv_nsec = remaining;
85 nanosleep (&duration, NULL);