| 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 | |||
| 5 | #ifndef STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_ | ||
| 6 | #define STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_ | ||
| 7 | |||
| 8 | #include "port/port.h" | ||
| 9 | |||
| 10 | namespace leveldb { | ||
| 11 | |||
| 12 | // Helper class that locks a mutex on construction and unlocks the mutex when | ||
| 13 | // the destructor of the MutexLock object is invoked. | ||
| 14 | // | ||
| 15 | // Typical usage: | ||
| 16 | // | ||
| 17 | // void MyClass::MyMethod() { | ||
| 18 | // MutexLock l(&mu_); // mu_ is an instance variable | ||
| 19 | // ... some complex code, possibly with multiple return paths ... | ||
| 20 | // } | ||
| 21 | |||
| 22 | class MutexLock { | ||
| 23 | public: | ||
| 24 | 0 | explicit MutexLock(port::Mutex *mu) : mu_(mu) { | |
| 25 | 0 | this->mu_->Lock(); | |
| 26 | 0 | } | |
| 27 | 0 | ~MutexLock() { this->mu_->Unlock(); } | |
| 28 | |||
| 29 | private: | ||
| 30 | port::Mutex *const mu_; | ||
| 31 | // No copying allowed | ||
| 32 | MutexLock(const MutexLock&); | ||
| 33 | void operator=(const MutexLock&); | ||
| 34 | }; | ||
| 35 | |||
| 36 | } | ||
| 37 | |||
| 38 | |||
| 39 | #endif // STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_ |