X-Git-Url: https://git.saurik.com/apple/libpthread.git/blobdiff_plain/3404ec80a22ac38c97e573f77f7cbdf4bddc8ca9..964d3577b041867f776d8eb940bf4a1108ffb97c:/tests/once.c diff --git a/tests/once.c b/tests/once.c new file mode 100644 index 0000000..a7005fe --- /dev/null +++ b/tests/once.c @@ -0,0 +1,61 @@ +#define __DARWIN_NON_CANCELABLE 0 +#include +#include +#include +#include + +static pthread_once_t once = PTHREAD_ONCE_INIT; +static int x = 0; + +void cancelled(void) +{ + printf("thread cancelled.\n"); +} + +void oncef(void) +{ + printf("in once handler: %p\n", pthread_self()); + sleep(5); + x = 1; +} + +void* a(void *ctx) +{ + printf("a started: %p\n", pthread_self()); + pthread_cleanup_push((void*)cancelled, NULL); + pthread_once(&once, oncef); + pthread_cleanup_pop(0); + printf("a finished\n"); + return NULL; +} + +void* b(void *ctx) +{ + sleep(1); // give enough time for a() to get into pthread_once + printf("b started: %p\n", pthread_self()); + pthread_once(&once, oncef); + printf("b finished\n"); + return NULL; +} + +int main(void) +{ + pthread_t t1; + if (pthread_create(&t1, NULL, a, NULL) != 0) { + fprintf(stderr, "failed to create thread a."); + exit(1); + } + + pthread_t t2; + if (pthread_create(&t2, NULL, b, NULL) != 0) { + fprintf(stderr, "failed to create thread b."); + exit(1); + } + + sleep(2); + pthread_cancel(t1); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); + exit(0); +} \ No newline at end of file