crl_common_on_main.cpp 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. #include <crl/crl_on_main.h>
  8. #ifdef CRL_USE_COMMON_QUEUE
  9. #include <exception>
  10. namespace {
  11. crl::queue *Queue/* = nullptr*/;
  12. std::atomic<int> Counter/* = 0*/;
  13. crl::details::main_queue_pointer Lifetime;
  14. } // namespace
  15. namespace crl::details {
  16. void main_queue_pointer::grab() {
  17. auto counter = Counter.load(std::memory_order_acquire);
  18. while (true) {
  19. if (!counter) {
  20. return;
  21. } else if (Counter.compare_exchange_weak(counter, counter + 1)) {
  22. _pointer = Queue;
  23. return;
  24. }
  25. }
  26. }
  27. void main_queue_pointer::ungrab() {
  28. if (_pointer) {
  29. if (--Counter == 0) {
  30. delete _pointer;
  31. }
  32. _pointer = nullptr;
  33. }
  34. }
  35. void main_queue_pointer::create(main_queue_processor processor) {
  36. if (Counter.load(std::memory_order_acquire) != 0) {
  37. std::terminate();
  38. }
  39. Queue = new queue(processor);
  40. Counter.store(1, std::memory_order_release);
  41. _pointer = Queue;
  42. }
  43. } // namespace crl::details
  44. namespace crl {
  45. void init_main_queue(main_queue_processor processor) {
  46. Lifetime.create(processor);
  47. }
  48. } // namespace crl
  49. #endif // CRL_USE_COMMON_QUEUE