| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#include <aws/common/ref_count.h> |
| 6 |
|
| 7 |
#include <aws/common/clock.h> |
| 8 |
#include <aws/common/condition_variable.h> |
| 9 |
#include <aws/common/mutex.h> |
| 10 |
|
| 11 |
void aws_ref_count_init(struct aws_ref_count *ref_count, void *object, aws_simple_completion_callback *on_zero_fn) { |
| 12 |
aws_atomic_init_int(&ref_count->ref_count, 1); |
| 13 |
ref_count->object = object; |
| 14 |
ref_count->on_zero_fn = on_zero_fn; |
| 15 |
} |
| 16 |
|
| 17 |
void *aws_ref_count_acquire(struct aws_ref_count *ref_count) { |
| 18 |
size_t old_value = aws_atomic_fetch_add(&ref_count->ref_count, 1); |
| 19 |
AWS_ASSERT(old_value > 0 && "refcount has been zero, it's invalid to use it again."); |
| 20 |
(void)old_value; |
| 21 |
|
| 22 |
return ref_count->object; |
| 23 |
} |
| 24 |
|
| 25 |
size_t aws_ref_count_release(struct aws_ref_count *ref_count) { |
| 26 |
size_t old_value = aws_atomic_fetch_sub(&ref_count->ref_count, 1); |
| 27 |
AWS_ASSERT(old_value > 0 && "refcount has gone negative"); |
| 28 |
if (old_value == 1) { |
| 29 |
ref_count->on_zero_fn(ref_count->object); |
| 30 |
} |
| 31 |
|
| 32 |
return old_value - 1; |
| 33 |
} |