instrumented_mutex.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #pragma once
  6. #include "monitoring/statistics.h"
  7. #include "port/port.h"
  8. #include "rocksdb/env.h"
  9. #include "rocksdb/statistics.h"
  10. #include "rocksdb/thread_status.h"
  11. #include "util/stop_watch.h"
  12. namespace ROCKSDB_NAMESPACE {
  13. class InstrumentedCondVar;
  14. // A wrapper class for port::Mutex that provides additional layer
  15. // for collecting stats and instrumentation.
  16. class InstrumentedMutex {
  17. public:
  18. explicit InstrumentedMutex(bool adaptive = false)
  19. : mutex_(adaptive), stats_(nullptr), env_(nullptr),
  20. stats_code_(0) {}
  21. InstrumentedMutex(
  22. Statistics* stats, Env* env,
  23. int stats_code, bool adaptive = false)
  24. : mutex_(adaptive), stats_(stats), env_(env),
  25. stats_code_(stats_code) {}
  26. void Lock();
  27. void Unlock() {
  28. mutex_.Unlock();
  29. }
  30. void AssertHeld() {
  31. mutex_.AssertHeld();
  32. }
  33. private:
  34. void LockInternal();
  35. friend class InstrumentedCondVar;
  36. port::Mutex mutex_;
  37. Statistics* stats_;
  38. Env* env_;
  39. int stats_code_;
  40. };
  41. // A wrapper class for port::Mutex that provides additional layer
  42. // for collecting stats and instrumentation.
  43. class InstrumentedMutexLock {
  44. public:
  45. explicit InstrumentedMutexLock(InstrumentedMutex* mutex) : mutex_(mutex) {
  46. mutex_->Lock();
  47. }
  48. ~InstrumentedMutexLock() {
  49. mutex_->Unlock();
  50. }
  51. private:
  52. InstrumentedMutex* const mutex_;
  53. InstrumentedMutexLock(const InstrumentedMutexLock&) = delete;
  54. void operator=(const InstrumentedMutexLock&) = delete;
  55. };
  56. class InstrumentedCondVar {
  57. public:
  58. explicit InstrumentedCondVar(InstrumentedMutex* instrumented_mutex)
  59. : cond_(&(instrumented_mutex->mutex_)),
  60. stats_(instrumented_mutex->stats_),
  61. env_(instrumented_mutex->env_),
  62. stats_code_(instrumented_mutex->stats_code_) {}
  63. void Wait();
  64. bool TimedWait(uint64_t abs_time_us);
  65. void Signal() {
  66. cond_.Signal();
  67. }
  68. void SignalAll() {
  69. cond_.SignalAll();
  70. }
  71. private:
  72. void WaitInternal();
  73. bool TimedWaitInternal(uint64_t abs_time_us);
  74. port::CondVar cond_;
  75. Statistics* stats_;
  76. Env* env_;
  77. int stats_code_;
  78. };
  79. } // namespace ROCKSDB_NAMESPACE