tc_spin_lock.h 720 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 
  2. #ifndef __TC_SPIN_LOCK_H
  3. #define __TC_SPIN_LOCK_H
  4. #include "util/tc_platform.h"
  5. #include <atomic>
  6. #include <memory>
  7. using namespace std;
  8. namespace tars
  9. {
  10. /**
  11. * 自旋锁
  12. * 不能阻塞wait, 只能快速加解锁, 适用于锁粒度非常小的情况, 减小线程切换的开销
  13. * 不支持trylock
  14. */
  15. class UTIL_DLL_API TC_SpinLock
  16. {
  17. public:
  18. TC_SpinLock();
  19. virtual ~TC_SpinLock();
  20. void lock() const;
  21. bool tryLock() const;
  22. void unlock() const;
  23. private:
  24. TC_SpinLock(const TC_SpinLock&) = delete;
  25. TC_SpinLock(TC_SpinLock&&) = delete;
  26. TC_SpinLock& operator=(const TC_SpinLock&) = delete;
  27. TC_SpinLock& operator=(TC_SpinLock&&) = delete;
  28. private:
  29. mutable std::atomic_flag _flag;
  30. };
  31. }
  32. #endif