Scope Lock模式线程Mutex

Scope Lock模式线程Mutex(一)

http://cplus.abang.com/od/cplus/a/scopedmutex1.htm

在《Unix下的线程互斥量》一文中我们使用Thread_Mutex来保护线程共享资源,但如果互斥体上锁之后没有解锁就会发生死锁。这是一个很普遍的错误,我们采用Scope Lock模式,我们构造对象Scope_Mutex,其中构造函数对互斥体加锁,析构函数对互斥体解锁。C++保证了析构函数一定会被调用,所以即使是有异常抛出,互斥体也总是会被正确的解锁。下面给出Scope_Mutex的具体实现:
class Scope_Mutex 
{ 
private: 
     Thread_Mutex& mMutex; 
     Scope_Mutex(const Scope_Mutex&); 
     Scope_Mutex& operator=(const Scope_Mutex&); 
public: 
     // 构造时对互斥量进行加锁 
     explicit Scope_Mutex(mMutex;& m) : mMutex;(m) 
    { mMutex.lock(); } 
    // 析构时对互斥量进行解锁
    ~Scope_Mutex() 
    { mMutex.unlock(); } 
}; 
 
 
class Thread_Mutex 
{ 
public: 
/* * 构造函数 */ 
Thread_Mutex() 
{ assert(pthread_mutex_init(&_mutex, NULL) == 0); } 


/* * 析造函数 */ 
~Thread_Mutex() 
{ //销毁互斥量 pthread_mutex_destroy(&_mutex); } 


/* * 加锁 */ 
void lock () 
{
     int error; 
     //锁住互斥量 
     error = pthread_mutex_lock(&_mutex); 
     if (error != 0) 
     { 
	   errno = error; 
	   perror("Mutex lock"); 
	   abort(); 
	 } 
} 


/* * 解锁 */ 
void unlock() 
{ 
     int error; 
     //解锁互斥量 
     error = pthread_mutex_unlock(&_mutex); 
     if (error != 0) 
     { 
	      errno = error; 
		  perror("Mutex unlock"); 
		  abort(); 
    } 
} 

protected: 
      pthread_mutex_t _mutex; 
};
 下一章我们将给出如何使用Scope_Mutex。
 
 

Scope Lock模式线程Mutex(二)

http://cplus.abang.com/od/cplus/a/scopedmutex2.htm
上一章给出了Scope_Mutex的具体实现,现在,我们使用Scope_Mutex对number进行保护,具体步骤如下: 
第一步:在线程函数前面使用Thread_Mutex构造Scope_Mutex   
第二步:对number加1,并打印结果 
第三步:在程序走出Scope_Mutex作用域,C++自动调用Scope_Mutex的析构函数来对Thread_Mutex对象进行?析构。   
下面给出实现具体代码: 
 
 int number; 
 Thread_Mutex tm;  
 
 void* f1(void* arg) 
 { 
     int tmp_number; 
     while(true) 
     { 
        Scope_Mutex(tm); 
        tmp_number = number; 
        number+=1; 
        usleep(5); 
        std::cout << "thread " << pthread_self() << ": number " << tmp_number << " increment by 1 is " << number << std::endl; 
     } 
     return NULL; 
 }  
 
 void* f2(void* arg) 
 { 
      int tmp_number; 
      while(true) 
      { 
         Scope_Mutex(tm); 
         tmp_number = number; 
         number+=1; 
         usleep(3); 
         std::cout << "thread " << pthread_self() << ": number " << tmp_number << " increment by 1 is " << number << std::endl; 
      } 
      return NULL; 
 }
 
 int main(void) 
 { 
      pthread_t tid1,tid2; 
      //create first thread; 
      pthread_create(&tid1, NULL, f1, NULL); 
      //create second thread; 
      pthread_create(&tid2, NULL, f2, NULL); 
      pthread_join(tid1,NULL); 
      pthread_join(tid2,NULL); 
      return 0; 
 } 
 
 执行上述程序,发现采用Scope_Mutex来保护共享资源—number,与单独采用Thread_Mutex保护number变量效果相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值