Skip to content

Commit 8795630

Browse files
authored
Fix thread termination example (bytecodealliance#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.
1 parent 9cf55f9 commit 8795630

File tree

1 file changed

+29
-26
lines changed

1 file changed

+29
-26
lines changed

samples/wasi-threads/wasm-apps/thread_termination.c

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -36,29 +36,41 @@ run_long_task()
3636
}
3737

3838
void
39-
__wasi_thread_start_C(int thread_id, int *start_arg)
39+
start_job()
4040
{
41-
shared_t *data = (shared_t *)start_arg;
41+
sem_post(&sem);
42+
run_long_task(); // Wait to be interrupted
43+
assert(false && "Unreachable");
44+
}
4245

43-
if (data->throw_exception) {
44-
// Wait for all other threads (including main thread) to be ready
45-
printf("Waiting before terminating\n");
46-
for (int i = 0; i < NUM_THREADS; i++)
47-
sem_wait(&sem);
46+
void
47+
terminate_process()
48+
{
49+
// Wait for all other threads (including main thread) to be ready
50+
printf("Waiting before terminating\n");
51+
for (int i = 0; i < NUM_THREADS; i++)
52+
sem_wait(&sem);
4853

49-
printf("Force termination\n");
54+
printf("Force termination\n");
5055
#if TEST_TERMINATION_BY_TRAP == 1
51-
__builtin_trap();
56+
__builtin_trap();
5257
#else
53-
__wasi_proc_exit(1);
58+
__wasi_proc_exit(1);
5459
#endif
60+
}
61+
62+
void
63+
__wasi_thread_start_C(int thread_id, int *start_arg)
64+
{
65+
shared_t *data = (shared_t *)start_arg;
66+
67+
if (data->throw_exception) {
68+
terminate_process();
5569
}
5670
else {
5771
printf("Thread running\n");
5872

59-
sem_post(&sem);
60-
run_long_task(); // Wait to be interrupted
61-
assert(false && "Unreachable");
73+
start_job();
6274
}
6375
}
6476

@@ -107,22 +119,13 @@ main(int argc, char **argv)
107119
return EXIT_FAILURE;
108120
}
109121

110-
printf("Main thread running\n");
111-
112-
sem_post(&sem);
113-
114122
#if TEST_TERMINATION_IN_MAIN_THREAD == 1
115-
116123
printf("Force termination (main thread)\n");
117-
#if TEST_TERMINATION_BY_TRAP == 1
118-
__builtin_trap();
119-
#else /* TEST_TERMINATION_BY_TRAP */
120-
__wasi_proc_exit(1);
121-
#endif /* TEST_TERMINATION_BY_TRAP */
122-
124+
terminate_process();
123125
#else /* TEST_TERMINATION_IN_MAIN_THREAD */
124-
run_long_task(); // Wait to be interrupted
125-
assert(false && "Unreachable");
126+
printf("Main thread running\n");
127+
128+
start_job();
126129
#endif /* TEST_TERMINATION_IN_MAIN_THREAD */
127130
return EXIT_SUCCESS;
128131
}

0 commit comments

Comments
 (0)