c11: Improve mtx_timedlock to use timespec_get instead of time(NULL)

Signed-off-by: Yonggang Luo <luoyonggang@gmail.com>
Reviewed-by: Jesse Natalie <jenatali@microsoft.com>
Acked-by: David Heidelberg <david.heidelberg@collabora.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/23733>
This commit is contained in:
Yonggang Luo 2023-02-13 11:07:59 +08:00 committed by Marge Bot
parent 66a99f619f
commit 45bd24708a

View file

@ -202,6 +202,21 @@ mtx_lock(mtx_t *mtx)
return (pthread_mutex_lock(mtx) == 0) ? thrd_success : thrd_error;
}
static int
threads_timespec_compare(struct timespec *a, struct timespec *b)
{
if (a->tv_sec < b->tv_sec) {
return -1;
} else if (a->tv_sec > b->tv_sec) {
return 1;
} else if (a->tv_nsec < b->tv_nsec) {
return -1;
} else if (a->tv_nsec > b->tv_nsec) {
return 1;
}
return 0;
}
// 7.25.4.4
int
mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
@ -217,11 +232,12 @@ mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
return thrd_success;
return (rt == ETIMEDOUT) ? thrd_timedout : thrd_error;
#else
time_t expire = time(NULL);
expire += ts->tv_sec;
while (mtx_trylock(mtx) != thrd_success) {
time_t now = time(NULL);
if (expire < now)
struct timespec now;
if (timespec_get(&now, TIME_UTC) != TIME_UTC) {
return thrd_error;
}
if (threads_timespec_compare(ts, &now) < 0)
return thrd_timedout;
// busy loop!
thrd_yield();