Path: blob/main/test/atomic/test_wait_suspending.c
14365 views
#include <emscripten.h>1#include <emscripten/wasm_worker.h>2#include <emscripten/threading.h>3#include <assert.h>45// Test emscripten_atomic_wait_suspending() function.67_Atomic int addr = 1;89void run_test() {10emscripten_out("worker running");11#if __EMSCRIPTEN_WASM_WORKERS__12emscripten_wasm_worker_sleep(1000 * 1000000ull); // Sleep one second.13#else14emscripten_thread_sleep(1000); // Sleep one second.15#endif16emscripten_out("worker: addr = 1234");17addr = 1234;18emscripten_out("worker: notify async waiting main thread");19emscripten_atomic_notify((int32_t*)&addr, 1);20}212223// This test run in both wasm workers and pthreads mode24#ifdef __EMSCRIPTEN_WASM_WORKERS__2526void worker_main() {27run_test();28}2930#else3132pthread_t t;3334bool done = false;3536void keepalive(void* user_data) {37if (!done) {38emscripten_set_timeout(keepalive, 100, NULL);39}40}4142void* thread_main(void* arg) {43run_test();44return 0;45}4647#endif4849int main() {50emscripten_out("main: creating worker");5152#ifdef __EMSCRIPTEN_WASM_WORKERS__53emscripten_wasm_worker_t worker = emscripten_malloc_wasm_worker(4096);54emscripten_wasm_worker_post_function_v(worker, worker_main);55#else56pthread_create(&t, NULL, thread_main, NULL);57// This is bit of hack to keep the node process alive. Without this,58// the whole node process will exit when we suspend them main thread below.59emscripten_set_timeout(keepalive, 100, NULL);60#endif6162ATOMICS_WAIT_TOKEN_T ret;6364emscripten_out("Async waiting on address with unexpected value should return 'not-equal'");65ret = emscripten_atomic_wait_suspending((int32_t*)&addr, 2, EMSCRIPTEN_WAIT_ASYNC_INFINITY);66assert(ret == ATOMICS_WAIT_NOT_EQUAL);6768emscripten_out("Waiting on address with unexpected value should return 'not-equal' also if timeout==0");69ret = emscripten_atomic_wait_suspending((int32_t*)&addr, 2, 0);70assert(ret == ATOMICS_WAIT_NOT_EQUAL);7172emscripten_out("Waiting for 0 milliseconds should return 'timed-out'");73ret = emscripten_atomic_wait_suspending((int32_t*)&addr, 1, 0);74assert(ret == ATOMICS_WAIT_TIMED_OUT);7576emscripten_out("Waiting for >0 milliseconds should also timeout");77ret = emscripten_atomic_wait_suspending((int32_t*)&addr, 1, 10);78assert(ret == ATOMICS_WAIT_TIMED_OUT);7980emscripten_out("Waiting for infinitely long should return once we have been notified");81ret = emscripten_atomic_wait_suspending((int32_t*)&addr, 1, EMSCRIPTEN_WAIT_ASYNC_INFINITY);82assert(ret == ATOMICS_WAIT_OK);83assert(addr == 1234);8485#ifdef __EMSCRIPTEN_WASM_WORKERS__86emscripten_terminate_all_wasm_workers();87#else88done = true;89pthread_join(t, NULL);90#endif9192emscripten_out("test finished");93return 0;94}959697