Просмотр исходного кода

Fix thread termination example (#1915)

The example wasn't fully implemented the intention - it didn't work as
expected when the trap/proc_exit was executed on the main thread,
because main thread never waited for all the threads to start.
Marcin Kolny 3 лет назад
Родитель
Сommit
879563047f
1 измененных файлов с 29 добавлено и 26 удалено
  1. 29 26
      samples/wasi-threads/wasm-apps/thread_termination.c

+ 29 - 26
samples/wasi-threads/wasm-apps/thread_termination.c

@@ -36,29 +36,41 @@ run_long_task()
 }
 
 void
-__wasi_thread_start_C(int thread_id, int *start_arg)
+start_job()
 {
-    shared_t *data = (shared_t *)start_arg;
+    sem_post(&sem);
+    run_long_task(); // Wait to be interrupted
+    assert(false && "Unreachable");
+}
 
-    if (data->throw_exception) {
-        // Wait for all other threads (including main thread) to be ready
-        printf("Waiting before terminating\n");
-        for (int i = 0; i < NUM_THREADS; i++)
-            sem_wait(&sem);
+void
+terminate_process()
+{
+    // Wait for all other threads (including main thread) to be ready
+    printf("Waiting before terminating\n");
+    for (int i = 0; i < NUM_THREADS; i++)
+        sem_wait(&sem);
 
-        printf("Force termination\n");
+    printf("Force termination\n");
 #if TEST_TERMINATION_BY_TRAP == 1
-        __builtin_trap();
+    __builtin_trap();
 #else
-        __wasi_proc_exit(1);
+    __wasi_proc_exit(1);
 #endif
+}
+
+void
+__wasi_thread_start_C(int thread_id, int *start_arg)
+{
+    shared_t *data = (shared_t *)start_arg;
+
+    if (data->throw_exception) {
+        terminate_process();
     }
     else {
         printf("Thread running\n");
 
-        sem_post(&sem);
-        run_long_task(); // Wait to be interrupted
-        assert(false && "Unreachable");
+        start_job();
     }
 }
 
@@ -107,22 +119,13 @@ main(int argc, char **argv)
         return EXIT_FAILURE;
     }
 
-    printf("Main thread running\n");
-
-    sem_post(&sem);
-
 #if TEST_TERMINATION_IN_MAIN_THREAD == 1
-
     printf("Force termination (main thread)\n");
-#if TEST_TERMINATION_BY_TRAP == 1
-    __builtin_trap();
-#else  /* TEST_TERMINATION_BY_TRAP */
-    __wasi_proc_exit(1);
-#endif /* TEST_TERMINATION_BY_TRAP */
-
+    terminate_process();
 #else  /* TEST_TERMINATION_IN_MAIN_THREAD */
-    run_long_task(); // Wait to be interrupted
-    assert(false && "Unreachable");
+    printf("Main thread running\n");
+
+    start_job();
 #endif /* TEST_TERMINATION_IN_MAIN_THREAD */
     return EXIT_SUCCESS;
 }