ref_count.c 1.1 KB

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