99 * musl/src/stdio/fwrite.c
1010 */
1111#include <assert.h>
12- #include <pthread.h>
1312#include <stdio.h>
1413#include <string.h>
1514#include <stdlib.h>
1615
16+ #ifdef __EMSCRIPTEN_PTHREADS__
17+ #include <pthread.h>
18+
1719pthread_t thread [2 ];
20+ #elif defined(__EMSCRIPTEN_WASM_WORKERS__ )
21+ #include <emscripten/wasm_worker.h>
22+ #include <emscripten/eventloop.h>
23+
24+ emscripten_wasm_worker_t worker [2 ];
25+ #else
26+ #error Expected to be compiled with either -sWASM_WORKERS or -pthread.
27+ #endif
28+
29+ #ifndef __wasm_atomics__
30+ #error Expected to be compiled with -matomics.
31+ #endif
32+
33+ #ifndef __wasm_bulk_memory__
34+ #error Expected to be compiled with -mbulk-memory.
35+ #endif
1836
1937char * char_repeat (int n , char c ) {
2038 char * dest = malloc (n + 1 );
@@ -23,23 +41,31 @@ char *char_repeat(int n, char c) {
2341 return dest ;
2442}
2543
26- void * thread_main (void * arg ) {
44+ void thread_main () {
2745 char * msg = char_repeat (100 , 'a' );
2846 for (int i = 0 ; i < 10 ; ++ i )
29- printf ("%s\n" , msg );
47+ printf ("%s\n" , msg );
3048 free (msg );
31- return 0 ;
3249}
3350
51+ #ifdef __EMSCRIPTEN_WASM_WORKERS__
52+ void terminate_worker (void * userData )
53+ {
54+ emscripten_terminate_all_wasm_workers ();
55+ printf ("main done\n" );
56+ }
57+ #endif
58+
3459int main () {
3560 printf ("in main\n" );
61+ #ifdef __EMSCRIPTEN_PTHREADS__
3662 void * thread_rtn ;
3763 int rc ;
3864
39- rc = pthread_create (& thread [0 ], NULL , thread_main , NULL );
65+ rc = pthread_create (& thread [0 ], NULL , ( void * ( * )( void * )) thread_main , NULL );
4066 assert (rc == 0 );
4167
42- rc = pthread_create (& thread [1 ], NULL , thread_main , NULL );
68+ rc = pthread_create (& thread [1 ], NULL , ( void * ( * )( void * )) thread_main , NULL );
4369 assert (rc == 0 );
4470
4571 rc = pthread_join (thread [0 ], & thread_rtn );
@@ -51,5 +77,14 @@ int main() {
5177 assert (thread_rtn == 0 );
5278
5379 printf ("main done\n" );
80+ #else
81+ worker [0 ] = emscripten_malloc_wasm_worker (/*stack size: */ 1024 );
82+ worker [1 ] = emscripten_malloc_wasm_worker (/*stack size: */ 1024 );
83+ emscripten_wasm_worker_post_function_v (worker [0 ], (void (* ))thread_main );
84+ emscripten_wasm_worker_post_function_v (worker [1 ], (void (* ))thread_main );
85+
86+ // Terminate both workers after a small delay
87+ emscripten_set_timeout (terminate_worker , 1000 , 0 );
88+ #endif
5489 return 0 ;
5590}
0 commit comments