-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrc_object.c
More file actions
86 lines (75 loc) · 1.71 KB
/
Copy pathrc_object.c
File metadata and controls
86 lines (75 loc) · 1.71 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <string.h>
#include <pthread.h>
typedef struct rc_object rc_object;
struct rc_object {
atomic_int refcnt;
void (*destroy)(rc_object *);
char payload[64];
};
static rc_object *rc_new(const char *msg)
{
rc_object *o = malloc(sizeof(rc_object));
if (!o) return NULL;
atomic_init(&o->refcnt, 1);
o->destroy = NULL;
strncpy(o->payload, msg, sizeof(o->payload) - 1);
o->payload[sizeof(o->payload) - 1] = 0;
return o;
}
static void rc_set_destroy(rc_object *o, void (*fn)(rc_object *))
{
o->destroy = fn;
}
static rc_object *rc_acquire(rc_object *o)
{
atomic_fetch_add_explicit(&o->refcnt, 1, memory_order_relaxed);
return o;
}
static void rc_release(rc_object *o)
{
int old = atomic_fetch_sub_explicit(&o->refcnt, 1, memory_order_acq_rel);
if (old == 1) {
if (o->destroy) o->destroy(o);
free(o);
}
}
static void rc_print(rc_object *o)
{
printf("rc_object[%p]: %s\n", (void *)o, o->payload);
}
static void custom_destroy(rc_object *o)
{
printf("destroying %p with payload=%s\n", (void *)o, o->payload);
}
typedef struct {
rc_object *o;
} arg_t;
static void *worker(void *p)
{
arg_t *a = p;
rc_object *o = rc_acquire(a->o);
rc_print(o);
rc_release(o);
return NULL;
}
int main(void)
{
rc_object *o = rc_new("shared object");
if (!o) return 1;
rc_set_destroy(o, custom_destroy);
pthread_t th[4];
arg_t a;
a.o = o;
for (int i = 0; i < 4; i++) {
pthread_create(&th[i], NULL, worker, &a);
}
for (int i = 0; i < 4; i++) {
pthread_join(th[i], NULL);
}
rc_release(o);
return 0;
}