crl_common_queue.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #pragma once
  8. #include <crl/common/crl_common_config.h>
  9. #include <crl/common/crl_common_list.h>
  10. #include <crl/common/crl_common_utils.h>
  11. #include <atomic>
  12. #ifndef CRL_USE_COMMON_QUEUE
  13. #define CRL_USE_COMMON_QUEUE
  14. #endif // !CRL_USE_COMMON_QUEUE
  15. namespace crl {
  16. namespace details {
  17. class main_queue_pointer;
  18. } // namespace details
  19. class queue {
  20. public:
  21. queue();
  22. queue(const queue &other) = delete;
  23. queue &operator=(const queue &other) = delete;
  24. template <typename Callable>
  25. void async(Callable &&callable) {
  26. if (_list.push_is_first(std::forward<Callable>(callable))) {
  27. wake_async();
  28. }
  29. }
  30. template <typename Callable>
  31. void sync(Callable &&callable) {
  32. semaphore waiter;
  33. async([&] {
  34. const auto guard = details::finally([&] { waiter.release(); });
  35. callable();
  36. });
  37. waiter.acquire();
  38. }
  39. private:
  40. friend class details::main_queue_pointer;
  41. static void ProcessCallback(void *that);
  42. queue(main_queue_processor processor);
  43. void wake_async();
  44. void process();
  45. main_queue_processor _main_processor = nullptr;
  46. details::list _list;
  47. std::atomic_flag _queued = ATOMIC_FLAG_INIT;
  48. };
  49. } // namespace crl