33
44#include <string.h>
55
6+ #if defined(__EMSCRIPTEN__ )
7+ #include <emscripten/threading.h>
8+ #include <emscripten/atomic.h>
9+ #include <math.h>
10+ #include <errno.h>
11+ #endif
12+
613#if defined(_MSC_VER ) || defined(__MINGW32__ ) || defined(__MINGW64__ )
714
815#include <winsock2.h>
@@ -57,11 +64,18 @@ sockevent_init(struct sockevent *e) {
5764 e -> pipe [0 ] = socket_invalid ;
5865 e -> pipe [1 ] = socket_invalid ;
5966
67+ #if defined(__EMSCRIPTEN__ )
68+ atomic_init (& e -> e , 0 );
69+ #else
6070 atomic_int_init (& e -> e , 0 );
71+ #endif
6172}
6273
6374static inline void
6475sockevent_close (struct sockevent * e ) {
76+ #if defined(__EMSCRIPTEN__ )
77+ atomic_store_explicit (& e -> e , 0 , memory_order_relaxed );
78+ #else
6579 if (e -> pipe [0 ] != socket_invalid ) {
6680 closesocket (e -> pipe [0 ]);
6781 e -> pipe [0 ] = socket_invalid ;
@@ -70,10 +84,15 @@ sockevent_close(struct sockevent *e) {
7084 closesocket (e -> pipe [1 ]);
7185 e -> pipe [1 ] = socket_invalid ;
7286 }
87+ #endif
7388}
7489
7590static inline int
7691sockevent_open (struct sockevent * e ) {
92+ #if defined(__EMSCRIPTEN__ )
93+ atomic_store_explicit (& e -> e , 0 , memory_order_relaxed );
94+ return 0 ;
95+ #else
7796 if (e -> pipe [0 ] != socket_invalid )
7897 return 0 ;
7998 socket_t fd = socket (AF_INET6 , SOCK_STREAM , 0 );
@@ -131,10 +150,16 @@ sockevent_open(struct sockevent *e) {
131150 closesocket (fd );
132151 sockevent_close (e );
133152 return -1 ;
153+ #endif
134154}
135155
136156static inline void
137157sockevent_trigger (struct sockevent * e ) {
158+ #if defined(__EMSCRIPTEN__ )
159+ if (atomic_exchange_explicit (& e -> e , 1 , memory_order_release ) == 0 ) {
160+ emscripten_futex_wake ((volatile void * )& e -> e , 1 );
161+ }
162+ #else
138163 if (e -> pipe [0 ] == socket_invalid )
139164 return ;
140165 if (atomic_int_load (& e -> e ))
@@ -147,14 +172,26 @@ sockevent_trigger(struct sockevent *e) {
147172#endif
148173 char tmp [1 ] = { 0 };
149174 send (e -> pipe [1 ], tmp , sizeof (tmp ), flags );
175+ #endif
150176}
151177
152178static inline int
153179sockevent_wait (struct sockevent * e ) {
180+ #if defined(__EMSCRIPTEN__ )
181+ for (;;) {
182+ if (atomic_exchange_explicit (& e -> e , 0 , memory_order_acquire ) != 0 ) {
183+ return 1 ;
184+ }
185+ int rc = emscripten_futex_wait ((volatile void * )& e -> e , 0 , INFINITY );
186+ if (rc != 0 && rc != - EWOULDBLOCK )
187+ return rc ;
188+ }
189+ #else
154190 char tmp [128 ];
155191 int r = recv (e -> pipe [0 ], tmp , sizeof (tmp ), 0 );
156192 atomic_int_store (& e -> e , 0 );
157193 return r ;
194+ #endif
158195}
159196
160197static inline socket_t
0 commit comments