标签:des style blog color 文件 sp div c on
由于pthread系列的函数都是成功时返回0,我们需要一段判断处理错误的代码:
#define TINY_CHECK(exp) if(!exp) { fprintf(stderr, "File : %s, Line : %d Exp : ["#exp"] is true, abort.\n", __FILE__, __LINE__); abort(); }
MutexLock的封装如下:
1 #ifndef MUTEXLOCK_H 2 #define MUTEXLOCK_H 3 4 #include "NonCopyable.h" 5 #include <pthread.h> 6 #define TINY_CHECK(exp) 7 if(!exp) 8 { 9 fprintf(stderr, "File : %s, Line : %d Exp : ["#exp"] is true, abort.\n", __FILE__, __LINE__); abort();10 } 11 12 class MutexLock : NonCopyable 13 { 14 public: 15 MutexLock(); 16 ~MutexLock(); 17 void lock(); 18 void unlock(); 19 20 bool isLocked() const { return _isLock; } 21 pthread_mutex_t *getMutexPtr() { return &_mutex; } 22 private: 23 pthread_mutex_t _mutex; 24 bool _isLock; 25 }; 26 27 #endif
cpp文件如下:
1 #include "MutexLock.h" 2 #include <assert.h> 3 4 MutexLock::MutexLock() 5 :_isLock(false) 6 { 7 TINY_CHECK(!pthread_mutex_init(&_mutex, NULL)); 8 } 9 10 MutexLock::~MutexLock() 11 { 12 assert(!isLocked()); 13 TINY_CHECK(!pthread_mutex_destroy(&_mutex)); 14 } 15 16 void MutexLock::lock() 17 { 18 TINY_CHECK(!pthread_mutex_lock(&_mutex)); 19 _isLock = true; 20 } 21 22 void MutexLock::unlock() 23 { 24 _isLock = false; 25 TINY_CHECK(!pthread_mutex_unlock(&_mutex)); 26 }
标签:des style blog color 文件 sp div c on
原文地址:http://www.cnblogs.com/gjn135120/p/4008559.html