async_joiner.h 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #pragma once
  2. #include <library/cpp/threading/future/future.h>
  3. namespace NUnifiedAgent {
  4. class TAsyncJoiner {
  5. public:
  6. inline TAsyncJoiner()
  7. : Promise(NThreading::NewPromise())
  8. , Refs(1)
  9. {
  10. }
  11. inline i64 Ref(i64 count = 1) noexcept {
  12. const auto result = Refs.fetch_add(count);
  13. Y_ABORT_UNLESS(result >= 1, "already joined");
  14. return result;
  15. }
  16. inline i64 UnRef() noexcept {
  17. const auto prev = Refs.fetch_sub(1);
  18. Y_ABORT_UNLESS(prev >= 1);
  19. if (prev == 1) {
  20. auto p = Promise;
  21. p.SetValue();
  22. }
  23. return prev;
  24. }
  25. inline NThreading::TFuture<void> Join() noexcept {
  26. auto result = Promise;
  27. UnRef();
  28. return result;
  29. }
  30. private:
  31. NThreading::TPromise<void> Promise;
  32. std::atomic<i64> Refs;
  33. };
  34. using TAsyncJoinerToken = TIntrusivePtr<TAsyncJoiner>;
  35. }