RAII手法是 Resource Acquisition is Initialization 的缩写,意为“资源获取即初始化”,在使用智能指针时也使用,下面是针对互斥量时的实现,
1 #include <iostream> 2 #include <pthread.h> 3 4 using namespace std; 5 6 class MutexLock 7 { 8 public: 9 MutexLock() 10 { 11 pthread_mutex_init(&mutex_, NULL); 12 } 13 14 ~MutexLock() 15 { 16 pthread_mutex_destroy(&mutex_); 17 } 18 19 void Lock() 20 { 21 pthread_mutex_lock(&mutex_); 22 } 23 24 void Unlock() 25 { 26 pthread_mutex_unlock(&mutex_); 27 } 28 29 private: 30 MutexLock(const MutexLock&); 31 MutexLock& operator=(const MutexLock&); 32 pthread_mutex_t mutex_; 33 }; 34 35 class MutexLockGuard 36 { 37 public: 38 explicit MutexLockGuard(MutexLock& mutex): mutex_(mutex) 39 { 40 mutex_.Lock(); 41 } 42 43 ~MutexLockGuard() 44 { 45 mutex_.Unlock(); 46 } 47 48 private: 49 MutexLockGuard(const MutexLockGuard&); 50 MutexLockGuard& operator=(const MutexLockGuard&); 51 52 MutexLock& mutex_; 53 }; 54 55 class Foo 56 { 57 public: 58 void print() 59 { 60 MutexLockGuard lock(mutex_); 61 cout << "Hello" << endl; 62 } 63 64 private: 65 MutexLock mutex_; 66 };
时间: 2024-11-08 01:50:48