|
| 1 | +// A joinable thread's "finished" message only reaches the main thread once it |
| 2 | +// returns to the event loop. By then the main thread has joined that thread |
| 3 | +// and created a new one that reuses its pthread_t. The late message must not |
| 4 | +// stop the new, still running thread from taking part in dlopen()'s sync. |
| 5 | + |
| 6 | +#include <assert.h> |
| 7 | +#include <dlfcn.h> |
| 8 | +#include <emscripten/eventloop.h> |
| 9 | +#include <emscripten/threading.h> |
| 10 | +#include <limits.h> |
| 11 | +#include <math.h> |
| 12 | +#include <pthread.h> |
| 13 | +#include <stdio.h> |
| 14 | +#include <stdlib.h> |
| 15 | + |
| 16 | +typedef int (*func_t)(); |
| 17 | + |
| 18 | +static pthread_t waiter; |
| 19 | +static _Atomic int go; |
| 20 | +static func_t (*side_func_address)(); |
| 21 | +static int result; |
| 22 | + |
| 23 | +static void* noop(void* arg) { return NULL; } |
| 24 | + |
| 25 | +static void* wait_then_call(void* arg) { |
| 26 | + while (!go) { |
| 27 | + emscripten_futex_wait(&go, 0, INFINITY); |
| 28 | + } |
| 29 | + if (side_func_address) { |
| 30 | + result = side_func_address()(); |
| 31 | + } |
| 32 | + return NULL; |
| 33 | +} |
| 34 | + |
| 35 | +static void release_waiter() { |
| 36 | + go = 1; |
| 37 | + emscripten_futex_wake(&go, INT_MAX); |
| 38 | + pthread_join(waiter, NULL); |
| 39 | + go = 0; |
| 40 | +} |
| 41 | + |
| 42 | +static void load_and_call(void* arg) { |
| 43 | + void* handle = dlopen("libside.so", RTLD_NOW); |
| 44 | + assert(handle); |
| 45 | + side_func_address = dlsym(handle, "side_func_address"); |
| 46 | + assert(side_func_address); |
| 47 | + // The waiter traps here if dlopen() skipped it. |
| 48 | + release_waiter(); |
| 49 | + assert(result == 43); |
| 50 | + printf("done\n"); |
| 51 | + exit(0); |
| 52 | +} |
| 53 | + |
| 54 | +int main() { |
| 55 | + // The new thread almost always gets the joined thread's block back, but |
| 56 | + // retry rather than depend on it. |
| 57 | + for (int i = 0; i < 10; i++) { |
| 58 | + pthread_t joined; |
| 59 | + pthread_create(&joined, NULL, noop, NULL); |
| 60 | + pthread_join(joined, NULL); |
| 61 | + pthread_create(&waiter, NULL, wait_then_call, NULL); |
| 62 | + if (pthread_equal(waiter, joined)) { |
| 63 | + emscripten_set_timeout(load_and_call, 100, NULL); |
| 64 | + return 0; |
| 65 | + } |
| 66 | + release_waiter(); |
| 67 | + } |
| 68 | + printf("no thread reused a joined thread's pthread_t\n"); |
| 69 | + return 1; |
| 70 | +} |
0 commit comments