From 0f38bf024018e07031b94baa096bacea0b3d56d3 Mon Sep 17 00:00:00 2001 From: Elias Vanderstuyft Date: Mon, 15 Aug 2016 17:29:07 +0200 Subject: [PATCH] Fix periodic lag/stutter: ensure that tv_nsec<10e9 Each time when "ts.tv_nsec" became greater or equal than 10e9, the cnd_timedwait() function returned immediately, causing the thread to become a busy waiting loop (slowing the other thread, on which the current was waiting, down), until "ts.tv_nsec" became smaller than 10e9. This caused noticeable stutter one 10th of a second, since the timeout was 100ms. --- examples/particles.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/examples/particles.c b/examples/particles.c index a035cb1e1..28e76fdd1 100644 --- a/examples/particles.c +++ b/examples/particles.c @@ -457,7 +457,12 @@ static void draw_particles(GLFWwindow* window, double t, float dt) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_nsec += 100000000; + ts.tv_nsec += 100 * 1000 * 1000; + if (ts.tv_nsec >= 1000 * 1000 * 1000) + { + ts.tv_sec++; + ts.tv_nsec -= 1000 * 1000 * 1000; + } cnd_timedwait(&thread_sync.p_done, &thread_sync.particles_lock, &ts); } @@ -908,7 +913,12 @@ static int physics_thread_main(void* arg) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_nsec += 100000000; + ts.tv_nsec += 100 * 1000 * 1000; + if (ts.tv_nsec >= 1000 * 1000 * 1000) + { + ts.tv_sec++; + ts.tv_nsec -= 1000 * 1000 * 1000; + } cnd_timedwait(&thread_sync.d_done, &thread_sync.particles_lock, &ts); }