You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.9 KiB

  1. #pragma once
  2. #include <mutex>
  3. #include <condition_variable>
  4. #include <ecs/config.h>
  5. namespace ecs {
  6. namespace core {
  7. namespace utils {
  8. /**
  9. * counter that blocks a given operation until it is equal zero
  10. */
  11. struct counter_blocker
  12. {
  13. protected:
  14. std::recursive_mutex _mutex; //!< mutex to preotect the counter
  15. std::condition_variable_any _cond_var; //!< conditional variable to synchronize the counter
  16. size_t _counter; //!< the actual counter value
  17. public:
  18. /**
  19. * constructor
  20. *
  21. * @param counter initial counter value
  22. */
  23. inline counter_blocker(size_t counter) noexcept;
  24. /**
  25. * increment the counter value by one
  26. */
  27. inline void increment() noexcept;
  28. /**
  29. * decrement the counter value by one and notify all pending threads
  30. */
  31. inline void decrement() noexcept;
  32. /**
  33. * execute the given function and wait until the counter is equal to zero
  34. *
  35. * @tparam T_func type of the function to execute
  36. *
  37. * @param func function to execute before waiting for the counter
  38. */
  39. template<typename T_func>
  40. inline void execute_and_wait(T_func&& func);
  41. /**
  42. * Execute the given function and wait until the counter is equal to zero.
  43. * Execute the given tick function at least once and repeatedly if the counter value has changed.
  44. *
  45. * @tparam T_func type of the function to execute
  46. * @tparam T_tick type of tick function to execute
  47. *
  48. * @param func function to execute before waiting for the counter
  49. * @param tick tick function to execute
  50. */
  51. template<typename T_func, typename T_tick>
  52. inline void execute_and_wait_tick(T_func&& func, T_tick&& tick);
  53. };
  54. } } }