上一篇博客讲了,Linux线程的包装器,既然用了了线程不可避免的要用到互斥量,所以下面给出了互斥量的包装器,也是在某一开源项目中看的,我略加删改,以突出重点。
Mutex.h
#ifndef _MUTEX_H_ #define _MUTEX_H_ #include <pthread.h> class Mutex { pthread_mutex_t mutexID; public: Mutex(); ~Mutex(); bool lock(); bool unlock(); }; #endif
Mutex.cpp
#include <Mutex.h> Mutex::Mutex() { pthread_mutex_init(&mutexID, NULL); } Mutex::~Mutex() { pthread_mutex_destroy(&mutexID); } bool Mutex::lock() { pthread_mutex_lock(&mutexID); return true; } bool Mutex::unlock() { pthread_mutex_unlock(&mutexID); return true; }
其中,只有显式的锁调用lock和unlock,现在还流行用scope lock的形式,就是巧妙的使用C++对象的生命周期来达到加锁的目的。