1 /** 2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 * SPDX-License-Identifier: Apache-2.0. 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 aws_ref_count_init(struct aws_ref_count * ref_count,void * object,aws_simple_completion_callback * on_zero_fn)11void 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 aws_ref_count_acquire(struct aws_ref_count * ref_count)17void *aws_ref_count_acquire(struct aws_ref_count *ref_count) { 18 aws_atomic_fetch_add(&ref_count->ref_count, 1); 19 20 return ref_count->object; 21 } 22 aws_ref_count_release(struct aws_ref_count * ref_count)23size_t aws_ref_count_release(struct aws_ref_count *ref_count) { 24 size_t old_value = aws_atomic_fetch_sub(&ref_count->ref_count, 1); 25 AWS_ASSERT(old_value > 0 && "refcount has gone negative"); 26 if (old_value == 1) { 27 ref_count->on_zero_fn(ref_count->object); 28 } 29 30 return old_value - 1; 31 } 32