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