1// excerpts from http://code.google.com/p/muduo/ 2// 3// Use of this source code is governed by a BSD-style license 4// that can be found in the License file. 5// 6// Author: Shuo Chen (giantchen at gmail dot com) 7 8#ifndef MUDUO_BASE_MUTEX_H 9#define MUDUO_BASE_MUTEX_H 10 11#include "Thread.h" 12 13#include <boost/noncopyable.hpp> 14#include <assert.h> 15#include <pthread.h> 16 17namespace muduo 18{ 19 20class MutexLock : boost::noncopyable 21{ 22 public: 23 MutexLock() 24 : holder_(0) 25 { 26 pthread_mutex_init(&mutex_, NULL); 27 } 28 29 ~MutexLock() 30 { 31 assert(holder_ == 0); 32 pthread_mutex_destroy(&mutex_); 33 } 34 35 bool isLockedByThisThread() 36 { 37 return holder_ == CurrentThread::tid(); 38 } 39 40 void assertLocked() 41 { 42 assert(isLockedByThisThread()); 43 } 44 45 // internal usage 46 47 void lock() 48 { 49 pthread_mutex_lock(&mutex_); 50 holder_ = CurrentThread::tid(); 51 } 52 53 void unlock() 54 { 55 holder_ = 0; 56 pthread_mutex_unlock(&mutex_); 57 } 58 59 pthread_mutex_t* getPthreadMutex() /* non-const */ 60 { 61 return &mutex_; 62 } 63 64 private: 65 66 pthread_mutex_t mutex_; 67 pid_t holder_; 68}; 69 70class MutexLockGuard : boost::noncopyable 71{ 72 public: 73 explicit MutexLockGuard(MutexLock& mutex) : mutex_(mutex) 74 { 75 mutex_.lock(); 76 } 77 78 ~MutexLockGuard() 79 { 80 mutex_.unlock(); 81 } 82 83 private: 84 85 MutexLock& mutex_; 86}; 87 88} 89 90// Prevent misuse like: 91// MutexLockGuard(mutex_); 92// A tempory object doesn't hold the lock for long! 93#define MutexLockGuard(x) error "Missing guard object name" 94 95#endif // MUDUO_BASE_MUTEX_H 96