test_sync.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. #include <util/system/condvar.h>
  3. #include <util/system/mutex.h>
  4. class TTestSync {
  5. private:
  6. unsigned Current;
  7. TMutex Mutex;
  8. TCondVar CondVar;
  9. public:
  10. TTestSync()
  11. : Current(0)
  12. {
  13. }
  14. void Inc() {
  15. TGuard<TMutex> guard(Mutex);
  16. DoInc();
  17. CondVar.BroadCast();
  18. }
  19. unsigned Get() {
  20. TGuard<TMutex> guard(Mutex);
  21. return Current;
  22. }
  23. void WaitFor(unsigned n) {
  24. TGuard<TMutex> guard(Mutex);
  25. Y_ABORT_UNLESS(Current <= n, "too late, waiting for %d, already %d", n, Current);
  26. while (n > Current) {
  27. CondVar.WaitI(Mutex);
  28. }
  29. }
  30. void WaitForAndIncrement(unsigned n) {
  31. TGuard<TMutex> guard(Mutex);
  32. Y_ABORT_UNLESS(Current <= n, "too late, waiting for %d, already %d", n, Current);
  33. while (n > Current) {
  34. CondVar.WaitI(Mutex);
  35. }
  36. DoInc();
  37. CondVar.BroadCast();
  38. }
  39. void CheckAndIncrement(unsigned n) {
  40. TGuard<TMutex> guard(Mutex);
  41. Y_ABORT_UNLESS(Current == n, "must be %d, currently %d", n, Current);
  42. DoInc();
  43. CondVar.BroadCast();
  44. }
  45. void Check(unsigned n) {
  46. TGuard<TMutex> guard(Mutex);
  47. Y_ABORT_UNLESS(Current == n, "must be %d, currently %d", n, Current);
  48. }
  49. private:
  50. void DoInc() {
  51. unsigned r = ++Current;
  52. Y_UNUSED(r);
  53. }
  54. };