陈硕老师《Linux 多线程服务端编程 使用muduo C++网络库》一书中对于MutexLock、MutexLockGuard的封装,主要用到了C++中的RAII技术。
MutexLock.cppclass MutexLock : boost::nocopyable { public: MutexLock() : holder_(0) { pthread_mutex_init(&mutex_, NULL); } ~MutexLock() { assert(holder_ == 0); pthread_mutex_destory(&mutex_); } bool isLockByThisThread() { return holder_ == CurrentThread::tid(); } void assertLocked() { assert(isLockByThisThread()); } void lock() { pthread_mutex_lock(&mutex_); holder_ = CurrentThread::tid(); } void unlock() { holder_ = 0; pthread_mutex_unlock(&mutex_); } pthread_mutex_t* getPthreadMutex() { return &mutex_; } private: pthread_mutex_t mutex_; pid_t holder_; };
|
MutexLockGuard.cppclass MutexLockGuard : boost::nocopyable { public: explicit MutexLockGuard(MutexLock& mutex) :mutex_(mutex) { mutex_.lock(); } ~MutexLockGuard() { mutex_.unlock(); } private: MutexLock& mutex_; }; #define MutexLockGuard(x) static_assert(false, "missing mutex guard var name")
|
注意上面代码的最后一行定义了一个宏,这个宏的作用是防止程序里出现如下错误:
test.cppvoid doit() { MutexLockGuard(mutex); }
|
Condition.cppclass Condition : boost::noncopyable { public: explicit Condition(MutexLock& mutex) : mutex_(mutex) { pthread_cond_init(&pcond_, NULL); } ~Condition() { pthread_cond_destory(&pcond_); } void wait() { pthread_cond_wait(&pcond_, mutex_.getPthreadMutex()); } void notify() { pthread_cond_signal(&pcond_); } void notifyAll() { pthread_cond_broadcast(&pcond_); } private: MutexLock& mutex_; pthread_cond_t pcond; }
|