mutexlock.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #ifndef STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
  5. #define STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
  6. #include "port/port.h"
  7. #include "port/thread_annotations.h"
  8. namespace leveldb {
  9. // Helper class that locks a mutex on construction and unlocks the mutex when
  10. // the destructor of the MutexLock object is invoked.
  11. //
  12. // Typical usage:
  13. //
  14. // void MyClass::MyMethod() {
  15. // MutexLock l(&mu_); // mu_ is an instance variable
  16. // ... some complex code, possibly with multiple return paths ...
  17. // }
  18. class SCOPED_LOCKABLE MutexLock {
  19. public:
  20. explicit MutexLock(port::Mutex* mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
  21. this->mu_->Lock();
  22. }
  23. ~MutexLock() UNLOCK_FUNCTION() { this->mu_->Unlock(); }
  24. MutexLock(const MutexLock&) = delete;
  25. MutexLock& operator=(const MutexLock&) = delete;
  26. private:
  27. port::Mutex* const mu_;
  28. };
  29. } // namespace leveldb
  30. #endif // STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_