Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/sockevent.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@

#include <string.h>

#if defined(__EMSCRIPTEN__)
#include <emscripten/threading.h>
#include <emscripten/atomic.h>
#include <math.h>
#include <errno.h>
#endif

#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)

#include <winsock2.h>
Expand Down Expand Up @@ -57,11 +64,18 @@ sockevent_init(struct sockevent *e) {
e->pipe[0] = socket_invalid;
e->pipe[1] = socket_invalid;

#if defined(__EMSCRIPTEN__)
atomic_init(&e->e, 0);
#else
atomic_int_init(&e->e, 0);
#endif
}

static inline void
sockevent_close(struct sockevent *e) {
#if defined(__EMSCRIPTEN__)
atomic_store_explicit(&e->e, 0, memory_order_relaxed);
#else
if (e->pipe[0] != socket_invalid) {
closesocket(e->pipe[0]);
e->pipe[0] = socket_invalid;
Expand All @@ -70,10 +84,15 @@ sockevent_close(struct sockevent *e) {
closesocket(e->pipe[1]);
e->pipe[1] = socket_invalid;
}
#endif
}

static inline int
sockevent_open(struct sockevent *e) {
#if defined(__EMSCRIPTEN__)
atomic_store_explicit(&e->e, 0, memory_order_relaxed);
return 0;
#else
if (e->pipe[0] != socket_invalid)
return 0;
socket_t fd = socket(AF_INET6, SOCK_STREAM, 0);
Expand Down Expand Up @@ -131,10 +150,16 @@ sockevent_open(struct sockevent *e) {
closesocket(fd);
sockevent_close(e);
return -1;
#endif
}

static inline void
sockevent_trigger(struct sockevent *e) {
#if defined(__EMSCRIPTEN__)
if (atomic_exchange_explicit(&e->e, 1, memory_order_release) == 0) {
emscripten_futex_wake((volatile void *)&e->e, 1);
}
#else
if (e->pipe[0] == socket_invalid)
return;
if (atomic_int_load(&e->e))
Expand All @@ -147,14 +172,26 @@ sockevent_trigger(struct sockevent *e) {
#endif
char tmp[1] = { 0 };
send(e->pipe[1], tmp, sizeof(tmp), flags);
#endif
}

static inline int
sockevent_wait(struct sockevent *e) {
#if defined(__EMSCRIPTEN__)
for (;;) {
if (atomic_exchange_explicit(&e->e, 0, memory_order_acquire) != 0) {
return 1;
}
int rc = emscripten_futex_wait((volatile void *)&e->e, 0, INFINITY);
if (rc != 0 && rc != -EWOULDBLOCK)
return rc;
}
#else
char tmp[128];
int r = recv(e->pipe[0], tmp, sizeof(tmp), 0);
atomic_int_store(&e->e, 0);
return r;
#endif
}

static inline socket_t
Expand Down