Skip to content

[POSIX] Wrong time diff after NTP syncronization #13

@andresmanelli

Description

@andresmanelli

Doing some tests I realized that if the tick is initialized before the first NTP synchronization, then the next diff is off, and the dispatch loop just hangs "forever" (in the case where events are already in the queue at least).

This is because the posix implementation uses gettimeofday, which is affected by NTP.

For me the solution was to use create a equeue_posix_monotonic.c and use clock_gettime, as in this patch:

diff --git a/equeue_posix.c b/equeue_posix.c
index 28bf5ae..b69f6d5 100644
--- a/equeue_posix.c
+++ b/equeue_posix.c
@@ -15,9 +15,9 @@
 
 // Tick operations
 unsigned equeue_tick(void) {
-    struct timeval tv;
-    gettimeofday(&tv, 0);
-    return (unsigned)(tv.tv_sec*1000 + tv.tv_usec/1000);
+    struct timespec tp;
+    (void) clock_gettime(CLOCK_MONOTONIC, &tp);
+    return (unsigned)(tp.tv_sec*1000 + tp.tv_nsec/1000000);
 }

Maybe something like this should be better:

diff --git a/equeue_posix.c b/equeue_posix.c
index 28bf5ae..6e2c787 100644
--- a/equeue_posix.c
+++ b/equeue_posix.c
@@ -15,9 +15,15 @@
 
 // Tick operations
 unsigned equeue_tick(void) {
+#ifdef _POSIX_MONOTONIC_CLOCK
+    struct timespec tp;
+    (void) clock_gettime(CLOCK_MONOTONIC, &tp);
+    return (unsigned)(tp.tv_sec*1000 + tp.tv_nsec/1000000);
+#else
     struct timeval tv;
     gettimeofday(&tv, 0);
     return (unsigned)(tv.tv_sec*1000 + tv.tv_usec/1000);
+#endif
 }

Let me know if this patch is something you'd be willing to include in the lib.

Thanks for equeue by the way !

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions