From 732e40dcfaa6a6c1be1b482f703790dc239f0ab8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Trevisan=20=28Trevi=C3=B1o=29?= Date: Fri, 14 Apr 2023 20:06:26 +0200 Subject: [PATCH] gtimer: Avoid doing anything on g_usleep (0) It's unlikely to happen, but still could be the case, so avoid do anything. --- glib/gtimer.c | 3 +++ glib/tests/timer.c | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/glib/gtimer.c b/glib/gtimer.c index d2d259918..dde502a15 100644 --- a/glib/gtimer.c +++ b/glib/gtimer.c @@ -269,6 +269,9 @@ g_timer_is_active (GTimer *timer) void g_usleep (gulong microseconds) { + if G_UNLIKELY (microseconds == 0) + return; + #ifdef G_OS_WIN32 /* Round up to the next millisecond */ Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0); diff --git a/glib/tests/timer.c b/glib/tests/timer.c index 3a2d1019c..be4cb957b 100644 --- a/glib/tests/timer.c +++ b/glib/tests/timer.c @@ -346,6 +346,29 @@ test_timeval_to_iso8601_overflow (void) g_assert_null (out); } +static void +test_usleep_with_zero_wait (void) +{ + GTimer *timer; + gdouble elapsed0, elapsed1; + + timer = g_timer_new (); + + g_timer_start (timer); + g_usleep (0); + elapsed0 = g_timer_elapsed (timer, NULL); + g_timer_stop (timer); + + g_timer_start (timer); + g_usleep (1); + elapsed1 = g_timer_elapsed (timer, NULL); + g_timer_stop (timer); + + g_assert_cmpfloat (elapsed0, <=, elapsed1); + + g_clear_pointer (&timer, g_timer_destroy); +} + int main (int argc, char *argv[]) { @@ -360,6 +383,7 @@ main (int argc, char *argv[]) g_test_add_func ("/timeval/from-iso8601", test_timeval_from_iso8601); g_test_add_func ("/timeval/to-iso8601", test_timeval_to_iso8601); g_test_add_func ("/timeval/to-iso8601/overflow", test_timeval_to_iso8601_overflow); + g_test_add_func ("/usleep/with-zero-wait", test_usleep_with_zero_wait); return g_test_run (); }