latch.h 954 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #pragma once
  2. #include <library/cpp/deprecated/atomic/atomic.h>
  3. #include <util/system/condvar.h>
  4. #include <util/system/mutex.h>
  5. class TLatch {
  6. private:
  7. // 0 for unlocked, 1 for locked
  8. TAtomic Locked;
  9. TMutex Mutex;
  10. TCondVar CondVar;
  11. public:
  12. TLatch()
  13. : Locked(0)
  14. {
  15. }
  16. void Wait() {
  17. // optimistic path
  18. if (AtomicGet(Locked) == 0) {
  19. return;
  20. }
  21. TGuard<TMutex> guard(Mutex);
  22. while (AtomicGet(Locked) == 1) {
  23. CondVar.WaitI(Mutex);
  24. }
  25. }
  26. bool TryWait() {
  27. return AtomicGet(Locked) == 0;
  28. }
  29. void Unlock() {
  30. // optimistic path
  31. if (AtomicGet(Locked) == 0) {
  32. return;
  33. }
  34. TGuard<TMutex> guard(Mutex);
  35. AtomicSet(Locked, 0);
  36. CondVar.BroadCast();
  37. }
  38. void Lock() {
  39. AtomicSet(Locked, 1);
  40. }
  41. bool IsLocked() {
  42. return AtomicGet(Locked);
  43. }
  44. };