本例子是模拟的读者写者问题,采用shared_ptr+写时拷贝实现,其中我觉得一个比较值得注意的地方是考虑到对象可能在临界区析构而将析构移除临界区,这对于多线程来说要多看多思。
#include#include #include #include #include #include #include #include using namespace std;using namespace boost;class Mutex:public noncopyable{//互斥量的封装 public: Mutex(){ pthread_mutex_init(&mutex,NULL); } void lock(){ pthread_mutex_lock(&mutex); } void unlock(){ pthread_mutex_unlock(&mutex); } ~Mutex(){ pthread_mutex_destroy(&mutex); } pthread_mutex_t* getMutex(){ return &mutex; } private: mutable pthread_mutex_t mutex;};class MutexLockGuard:noncopyable{//RAII管理互斥量 public: explicit MutexLockGuard(Mutex& mutex):mutex_(mutex){ mutex_.lock(); } ~MutexLockGuard(){ mutex_.unlock(); } private: Mutex& mutex_;//注意是引用,Mutex继承了noncopyable后不能拷贝构造};class test:noncopyable{ public: test():ptr(new vector ),mutex(){} void show(){ shared_ptr > temp=get(); for(vector ::iterator it=temp->begin();it!=temp->end();it++){ cout<<*it<<" "; } cout<