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.

55 lines
1.3 KiB

  1. #pragma once
  2. #include <mutex>
  3. #include <condition_variable>
  4. #include <ecs/config.h>
  5. beg_namespace_ecs_core_utils
  6. {
  7. struct counter_blocker
  8. {
  9. private:
  10. std::mutex _mutex;
  11. std::condition_variable _cond_var;
  12. size_t _counter;
  13. public:
  14. inline counter_blocker(size_t counter) noexcept
  15. : _counter(counter)
  16. { }
  17. inline void increment() noexcept
  18. {
  19. std::lock_guard lock(_mutex);
  20. assert(_counter > 0);
  21. ++_counter;
  22. }
  23. inline void decrement_and_notify_one() noexcept
  24. {
  25. std::lock_guard lock(_mutex);
  26. assert(_counter > 0);
  27. --_counter;
  28. _cond_var.notify_one();
  29. }
  30. inline void decrement_and_notify_all() noexcept
  31. {
  32. std::lock_guard lock(_mutex);
  33. assert(_counter > 0);
  34. --_counter;
  35. _cond_var.notify_all();
  36. }
  37. template<typename T_func>
  38. inline void execute_and_wait_until_zero(T_func&& func) noexcept
  39. {
  40. func();
  41. std::unique_lock lock(_mutex);
  42. _cond_var.wait(lock, [this]{ return (_counter == 0); });
  43. }
  44. };
  45. }
  46. end_namespace_ecs_core_utils