Skip to content

Commit

Permalink
Fix thread termination example (#1915)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
loganek authored Jan 25, 2023
1 parent 9cf55f9 commit 8795630
Showing 1 changed file with 29 additions and 26 deletions.
55 changes: 29 additions & 26 deletions samples/wasi-threads/wasm-apps/thread_termination.c
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

Expand Down Expand Up @@ -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;
}

0 comments on commit 8795630

Please sign in to comment.