async.h 1021 B

12345678910111213141516171819202122232425262728293031
  1. #pragma once
  2. #include "future.h"
  3. #include <util/generic/function.h>
  4. #include <util/thread/pool.h>
  5. namespace NThreading {
  6. /**
  7. * @brief Asynchronously executes @arg func in @arg queue returning a future for the result.
  8. *
  9. * @arg func should be a callable object with signature T().
  10. * @arg queue where @arg will be executed
  11. * @returns For @arg func with signature T() the function returns TFuture<T> unless T is TFuture<U>.
  12. * In this case the function returns TFuture<U>.
  13. *
  14. * If you want to use another queue for execution just write an overload, @see ExtensionExample
  15. * unittest.
  16. */
  17. template <typename Func>
  18. TFuture<TFutureType<TFunctionResult<Func>>> Async(Func&& func, IThreadPool& queue) {
  19. auto promise = NewPromise<TFutureType<TFunctionResult<Func>>>();
  20. auto lambda = [promise, func = std::forward<Func>(func)]() mutable {
  21. NImpl::SetValue(promise, func);
  22. };
  23. queue.SafeAddFunc(std::move(lambda));
  24. return promise.GetFuture();
  25. }
  26. }