async_result.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #pragma once
  2. #include <util/generic/maybe.h>
  3. #include <util/generic/noncopyable.h>
  4. #include <util/system/condvar.h>
  5. #include <util/system/mutex.h>
  6. #include <util/system/yassert.h>
  7. #include <functional>
  8. // probably this thing should have been called TFuture
  9. template <typename T>
  10. class TAsyncResult : TNonCopyable {
  11. private:
  12. TMutex Mutex;
  13. TCondVar CondVar;
  14. TMaybe<T> Result;
  15. typedef void TOnResult(const T&);
  16. std::function<TOnResult> OnResult;
  17. public:
  18. void SetResult(const T& result) {
  19. TGuard<TMutex> guard(Mutex);
  20. Y_ABORT_UNLESS(!Result, "cannot set result twice");
  21. Result = result;
  22. CondVar.BroadCast();
  23. if (!!OnResult) {
  24. OnResult(result);
  25. }
  26. }
  27. const T& GetResult() {
  28. TGuard<TMutex> guard(Mutex);
  29. while (!Result) {
  30. CondVar.Wait(Mutex);
  31. }
  32. return *Result;
  33. }
  34. template <typename TFunc>
  35. void AndThen(const TFunc& onResult) {
  36. TGuard<TMutex> guard(Mutex);
  37. if (!!Result) {
  38. onResult(*Result);
  39. } else {
  40. Y_ASSERT(!OnResult);
  41. OnResult = std::function<TOnResult>(onResult);
  42. }
  43. }
  44. };