contention_ut.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "counters.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/system/event.h>
  4. #include <util/system/thread.h>
  5. using namespace NMonitoring;
  6. Y_UNIT_TEST_SUITE(TDynamicCountersContentionTest) {
  7. Y_UNIT_TEST(EnsureNonlocking) {
  8. TDynamicCounterPtr counters = MakeIntrusive<TDynamicCounters>();
  9. class TConsumer : public ICountableConsumer {
  10. TAutoEvent Ev;
  11. TAutoEvent Response;
  12. TDynamicCounterPtr Counters;
  13. TThread Thread;
  14. public:
  15. TConsumer(TDynamicCounterPtr counters)
  16. : Counters(counters)
  17. , Thread(std::bind(&TConsumer::ThreadFunc, this))
  18. {
  19. Thread.Start();
  20. }
  21. ~TConsumer() override {
  22. Thread.Join();
  23. }
  24. void OnCounter(const TString& /*labelName*/, const TString& /*labelValue*/, const TCounterForPtr* /*counter*/) override {
  25. Ev.Signal();
  26. Response.Wait();
  27. }
  28. void OnHistogram(const TString& /*labelName*/, const TString& /*labelValue*/, IHistogramSnapshotPtr /*snapshot*/, bool /*derivative*/) override {
  29. }
  30. void OnGroupBegin(const TString& /*labelName*/, const TString& /*labelValue*/, const TDynamicCounters* /*group*/) override {
  31. }
  32. void OnGroupEnd(const TString& /*labelName*/, const TString& /*labelValue*/, const TDynamicCounters* /*group*/) override {
  33. }
  34. private:
  35. void ThreadFunc() {
  36. // acts like a coroutine
  37. Ev.Wait();
  38. auto ctr = Counters->GetSubgroup("label", "value")->GetCounter("name");
  39. Y_VERIFY(*ctr == 42);
  40. Response.Signal();
  41. }
  42. };
  43. auto ctr = counters->GetSubgroup("label", "value")->GetCounter("name");
  44. *ctr = 42;
  45. TConsumer consumer(counters);
  46. counters->Accept({}, {}, consumer);
  47. }
  48. }