1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <assert.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <emscripten/emscripten.h>
#include <emscripten/eventloop.h>
#include <emscripten/console.h>
#include <emscripten/proxying.h>
pthread_t t;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
bool running = false;
void timeout(void* arg) {
emscripten_err("timeout");
pthread_mutex_lock(&mutex);
running = true;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
void* thread_main(void* arg) {
// Keep the thread runtime alive for now.
emscripten_err("thread_main");
emscripten_runtime_keepalive_push();
emscripten_set_timeout(timeout, 0, NULL);
return NULL;
}
void say_hello(void* arg) {
emscripten_err("say_hello");
}
void keepalive_pop(void* arg) {
emscripten_err("keepalive_pop");
// After this the called, thread should exit (become joinable).
emscripten_runtime_keepalive_pop();
}
int main() {
printf("main\n");
pthread_mutex_lock(&mutex);
int rc = pthread_create(&t, NULL, thread_main, NULL);
assert(rc == 0);
// Wait until the thread is running from the event loop
while (!running) {
pthread_cond_wait(&cond, &mutex);
}
// Run something from the thread's event loop
emscripten_proxy_sync(emscripten_proxy_get_system_queue(), t, &say_hello, NULL);
// Run keepalive_pop, causing the thread to exit gracefully
emscripten_proxy_sync(emscripten_proxy_get_system_queue(), t, &keepalive_pop, NULL);
// Now the thread should be joinable
void* thread_rtn = 0;
rc = pthread_join(t, &thread_rtn);
assert(rc == 0);
printf("done join\n");
return 0;
}
|