BsSpinLock.h 792 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #pragma once
  2. #include <atomic>
  3. namespace BansheeEngine
  4. {
  5. /**
  6. * @brief Synchronization primitive with low overhead.
  7. *
  8. * @note However it will actively block the thread waiting for the lock,
  9. * not allowing any other work to be done, so it is best used for short
  10. * locks.
  11. */
  12. class SpinLock
  13. {
  14. public:
  15. SpinLock()
  16. {
  17. mLock.clear(std::memory_order_relaxed);
  18. }
  19. /**
  20. * @brief Lock any following operations with the spin lock, not allowing
  21. * any other thread to access them.
  22. */
  23. void lock()
  24. {
  25. while(mLock.test_and_set(std::memory_order_acquire))
  26. { }
  27. }
  28. /**
  29. * @brief Release the lock and allow other threads to acquire the lock.
  30. */
  31. void unlock()
  32. {
  33. mLock.clear(std::memory_order_release);
  34. }
  35. private:
  36. std::atomic_flag mLock;
  37. };
  38. }