From 879563047fbc47afb638588c609b9005faaa3c44 Mon Sep 17 00:00:00 2001 From: Marcin Kolny Date: Wed, 25 Jan 2023 01:34:36 +0000 Subject: [PATCH] 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. --- .../wasm-apps/thread_termination.c | 59 ++++++++++--------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/samples/wasi-threads/wasm-apps/thread_termination.c b/samples/wasi-threads/wasm-apps/thread_termination.c index 2adaa621f..dfc228eb3 100644 --- a/samples/wasi-threads/wasm-apps/thread_termination.c +++ b/samples/wasi-threads/wasm-apps/thread_termination.c @@ -35,30 +35,42 @@ run_long_task() sleep(1); } +void +start_job() +{ + sem_post(&sem); + run_long_task(); // Wait to be interrupted + assert(false && "Unreachable"); +} + +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"); +#if TEST_TERMINATION_BY_TRAP == 1 + __builtin_trap(); +#else + __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) { - // 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"); -#if TEST_TERMINATION_BY_TRAP == 1 - __builtin_trap(); -#else - __wasi_proc_exit(1); -#endif + 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; } +#if TEST_TERMINATION_IN_MAIN_THREAD == 1 + printf("Force termination (main thread)\n"); + terminate_process(); +#else /* TEST_TERMINATION_IN_MAIN_THREAD */ 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 */ - -#else /* TEST_TERMINATION_IN_MAIN_THREAD */ - run_long_task(); // Wait to be interrupted - assert(false && "Unreachable"); + start_job(); #endif /* TEST_TERMINATION_IN_MAIN_THREAD */ return EXIT_SUCCESS; } \ No newline at end of file