AsyncRunner.h 918 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * AsyncRunner.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include <tbb/task_arena.h>
  12. #include <tbb/task_group.h>
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. /// Helper class for running asynchronous tasks using TBB thread pool
  15. class AsyncRunner : boost::noncopyable
  16. {
  17. tbb::task_arena arena;
  18. tbb::task_group taskGroup;
  19. public:
  20. /// Runs the provided functor asynchronously on a thread from the TBB worker pool.
  21. template<typename Functor>
  22. void run(Functor && f)
  23. {
  24. arena.enqueue(taskGroup.defer(std::forward<Functor>(f)));
  25. }
  26. /// Waits for all previously enqueued task.
  27. /// Re-entrable - waiting for tasks does not prevent submitting new tasks
  28. void wait()
  29. {
  30. taskGroup.wait();
  31. }
  32. ~AsyncRunner()
  33. {
  34. wait();
  35. }
  36. };
  37. VCMI_LIB_NAMESPACE_END