async_semaphore.h 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #pragma once
  2. #include <library/cpp/threading/future/future.h>
  3. #include <util/system/spinlock.h>
  4. #include <util/generic/ptr.h>
  5. #include <list>
  6. #include <functional>
  7. namespace NThreading {
  8. class TAsyncSemaphore: public TThrRefBase {
  9. public:
  10. using TPtr = TIntrusivePtr<TAsyncSemaphore>;
  11. class TAutoRelease {
  12. public:
  13. TAutoRelease(TAsyncSemaphore::TPtr sem)
  14. : Sem(std::move(sem))
  15. {
  16. }
  17. TAutoRelease(TAutoRelease&& other)
  18. : Sem(std::move(other.Sem))
  19. {
  20. }
  21. ~TAutoRelease();
  22. std::function<void (const TFuture<void>&)> DeferRelease();
  23. private:
  24. TAsyncSemaphore::TPtr Sem;
  25. };
  26. static TPtr Make(size_t count);
  27. TFuture<TPtr> AcquireAsync();
  28. void Release();
  29. void Cancel();
  30. TAutoRelease MakeAutoRelease() {
  31. return {this};
  32. }
  33. private:
  34. TAsyncSemaphore(size_t count);
  35. private:
  36. size_t Count_;
  37. bool Cancelled_ = false;
  38. TAdaptiveLock Lock_;
  39. std::list<TPromise<TPtr>> Promises_;
  40. };
  41. } // namespace NThreading