Browse Source

posix iwasm: Make the timeout logic a bit more robust (#3478)

Use an absolute timeout calculation to avoid being affected much
by CPU scheduling.
YAMAMOTO Takashi 1 year ago
parent
commit
1f8a78d61a
1 changed files with 13 additions and 11 deletions
  1. 13 11
      product-mini/platforms/posix/main.c

+ 13 - 11
product-mini/platforms/posix/main.c

@@ -535,21 +535,23 @@ void *
 timeout_thread(void *vp)
 timeout_thread(void *vp)
 {
 {
     const struct timeout_arg *arg = vp;
     const struct timeout_arg *arg = vp;
-    uint32 left = arg->timeout_ms;
+    const uint64 end_time =
+        os_time_get_boot_us() + (uint64)arg->timeout_ms * 1000;
     while (!arg->cancel) {
     while (!arg->cancel) {
-        uint32 ms;
-        if (left >= 100) {
-            ms = 100;
-        }
-        else {
-            ms = left;
-        }
-        os_usleep((uint64)ms * 1000);
-        left -= ms;
-        if (left == 0) {
+        const uint64 now = os_time_get_boot_us();
+        if ((int64)(now - end_time) > 0) {
             wasm_runtime_terminate(arg->inst);
             wasm_runtime_terminate(arg->inst);
             break;
             break;
         }
         }
+        const uint64 left_us = end_time - now;
+        uint32 us;
+        if (left_us >= 100 * 1000) {
+            us = 100 * 1000;
+        }
+        else {
+            us = left_us;
+        }
+        os_usleep(us);
     }
     }
     return NULL;
     return NULL;
 }
 }