summaryrefslogtreecommitdiffhomepage
path: root/examples/sptr_pthread.c
diff options
context:
space:
mode:
authorTyge Løvset <[email protected]>2021-10-26 20:46:43 +0200
committerTyge Løvset <[email protected]>2021-10-26 20:46:43 +0200
commit0c6b41fd08bac55281ff9ad41b0d052171881651 (patch)
tree4a8107ce800eba0bd0d659d557133466e01da79c /examples/sptr_pthread.c
parent0f95c005891b0d4b3b2610fdba241cf78c372d81 (diff)
downloadSTC-modified-0c6b41fd08bac55281ff9ad41b0d052171881651.tar.gz
STC-modified-0c6b41fd08bac55281ff9ad41b0d052171881651.zip
Added some examples and updated docs. Removed cvec_X_erase() and cdeq_X_erase() - may be used wrong. Use cvec_X_erase_n() instead.
Fixed type-bug in cpque.h (same was in cqueue.h).
Diffstat (limited to 'examples/sptr_pthread.c')
-rw-r--r--examples/sptr_pthread.c61
1 files changed, 61 insertions, 0 deletions
diff --git a/examples/sptr_pthread.c b/examples/sptr_pthread.c
new file mode 100644
index 00000000..8957a118
--- /dev/null
+++ b/examples/sptr_pthread.c
@@ -0,0 +1,61 @@
+// example based on https://en.cppreference.com/w/cpp/memory/shared_ptr
+#if defined __GNUC__ || defined __linux__
+
+#include <stdio.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <time.h>
+
+struct Base
+{
+ int value;
+} typedef Base;
+
+void Base_del(Base* b) { printf("Base::~Base()\n"); }
+
+#define i_val Base
+#define i_cmp c_no_compare
+#define i_del Base_del
+#define i_tag base
+#include <stc/csptr.h>
+
+void* thr(csptr_base* lp)
+{
+ static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
+ sleep(1);
+ c_autoscope (pthread_mutex_lock(&mtx), pthread_mutex_unlock(&mtx))
+ {
+ printf("local pointer in a thread:\n"
+ " p.get() = %p, p.use_count() = %zu\n", lp->get, *lp->use_count);
+ }
+ /* atomically decrease ref. */
+ csptr_base_del(lp);
+ return NULL;
+}
+
+int main()
+{
+ csptr_base p = csptr_base_make((Base){42});
+
+ printf("Created a Base\n"
+ " p.get() = %p, p.use_count() = %zu\n", p.get, *p.use_count);
+ enum {N = 3};
+ pthread_t t[N];
+ csptr_base c[N];
+ c_forrange (i, N) {
+ c[i] = csptr_base_clone(p);
+ pthread_create(&t[i], NULL, (void*(*)(void*))thr, &c[i]);
+ }
+
+ printf("Shared ownership between %d threads and released\n"
+ "ownership from main:\n"
+ " p.get() = %p, p.use_count() = %zu\n", N, p.get, *p.use_count);
+ csptr_base_reset(&p);
+
+ c_forrange (i, N) pthread_join(t[i], NULL);
+ printf("All threads completed, the last one deleted Base\n");
+}
+
+#else
+int main() {}
+#endif \ No newline at end of file