General Purpose library for Freestanding C++ and POSIX systems
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

52 rindas
1.2 KiB

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