General Purpose library for Freestanding C++ and POSIX systems
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

57 řádky
1.3 KiB

před 3 roky
  1. #pragma once
  2. #include <atomic>
  3. #include "gp_config.hpp"
  4. namespace gp {
  5. /**
  6. * @brief CADR lock_guard for generic locking mechanisms
  7. *
  8. * @tparam T
  9. */
  10. template<typename T>
  11. class lock_guard {
  12. T& ref;
  13. public:
  14. lock_guard(T& _ref)
  15. : ref(_ref)
  16. {
  17. ref.lock();
  18. }
  19. ~lock_guard() {
  20. ref.unlock();
  21. }
  22. };
  23. /**
  24. * @brief A fast mutual exclusion handler WITHOUT deadlock detection
  25. */
  26. class fast_bottleneck {
  27. std::atomic_bool flag;
  28. public:
  29. fast_bottleneck() = default;
  30. fast_bottleneck(fast_bottleneck&) = delete;
  31. fast_bottleneck(fast_bottleneck&&) = delete;
  32. void lock() {
  33. while(not try_lock());
  34. }
  35. [[nodiscard]] bool try_lock() {
  36. bool f = false;
  37. bool t = true;
  38. return flag.compare_exchange_strong(f,t,std::memory_order::acquire);
  39. }
  40. void unlock() {
  41. gp_config::assertion(try_unlock(), "Unlocking failed in fast_bottleneck: potential double unlocking issue");
  42. }
  43. [[nodiscard]] bool try_unlock() {
  44. bool f = false;
  45. bool t = true;
  46. return flag.compare_exchange_strong(t,f,std::memory_order::release);
  47. }
  48. };
  49. }