From c325b265e322f09c6020c8d509bd9e965dba1985 Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Thu, 13 Jan 2022 17:48:39 +0100 Subject: Fixed threads_demo.c and made it "identical" to the c++ example. --- examples/threads_demo.c | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) (limited to 'examples') diff --git a/examples/threads_demo.c b/examples/threads_demo.c index a31c2662..667ffb5b 100644 --- a/examples/threads_demo.c +++ b/examples/threads_demo.c @@ -1,7 +1,6 @@ -// example based on https://en.cppreference.com/w/cpp/memory/shared_ptr +// Example translated to C from https://en.cppreference.com/w/cpp/memory/shared_ptr #include -#include #include #include @@ -10,7 +9,7 @@ struct Base int value; } typedef Base; -#define i_type BaseRc +#define i_type BaseArc #define i_val Base #define i_valdrop(x) printf("Drop Base: %d\n", (x)->value) #define i_opt c_no_cmp @@ -18,42 +17,43 @@ struct Base mtx_t mtx; -void* thr(BaseRc* lp) +void* thr(BaseArc* p) { - sleep(1); + thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // sleep 1 sec + BaseArc lp = BaseArc_clone(*p); // thread-safe, even though the + // shared use_count is incremented + c_autoscope (mtx_lock(&mtx), mtx_unlock(&mtx)) { printf("local pointer in a thread:\n" - " p.get() = %p, p.use_count() = %ld\n", (void*)lp->get, *lp->use_count); + " p.get() = %p, p.use_count() = %ld\n", (void*)lp.get, BaseArc_use_count(lp)); /* safe to modify base here */ - lp->get->value += 1; + lp.get->value += 1; } /* atomically decrease ref. */ - BaseRc_drop(lp); + BaseArc_drop(&lp); + BaseArc_drop(p); return NULL; } int main() { - BaseRc p = BaseRc_from((Base){0}); + BaseArc p = BaseArc_from((Base){0}); mtx_init(&mtx, mtx_plain); - printf("Created a Base\n" - " p.get() = %p, p.use_count() = %ld\n", (void*)p.get, *p.use_count); - enum {N = 3}; - thrd_t t[N]; - BaseRc c[N]; - c_forrange (i, N) { - c[i] = BaseRc_clone(p); - thrd_create(&t[i], (thrd_start_t)thr, &c[i]); - } - - printf("Shared ownership between %d threads and released\n" + printf("Created a shared Base\n" + " p.get() = %p, p.use_count() = %ld\n", (void*)p.get, BaseArc_use_count(p)); + thrd_t t1, t2, t3; + thrd_create(&t1, (thrd_start_t)thr, (BaseArc[]){BaseArc_clone(p)}); + thrd_create(&t2, (thrd_start_t)thr, (BaseArc[]){BaseArc_clone(p)}); + thrd_create(&t3, (thrd_start_t)thr, (BaseArc[]){BaseArc_clone(p)}); + + BaseArc_reset(&p); + printf("Shared ownership between 3 threads and released\n" "ownership from main:\n" - " p.get() = %p, p.use_count() = %ld\n", N, (void*)p.get, *p.use_count); - BaseRc_reset(&p); + " p.get() = %p, p.use_count() = %ld\n", (void*)p.get, BaseArc_use_count(p)); - c_forrange (i, N) thrd_join(t[i], NULL); + thrd_join(t1, NULL); thrd_join(t3, NULL); thrd_join(t3, NULL); printf("All threads completed, the last one deleted Base\n"); } -- cgit v1.2.3