标签:线程锁 type write uniq int image break div variable
多线程变量区域锁类定义
//写锁定义 typedef boost::shared_mutex Lock; typedef boost::unique_lock<Lock> WriteLock; typedef boost::shared_lock<Lock> ReadLock; // 区域互斥锁类定义 class CVariableLock { public: CVariableLock(Lock *lock, bool *lock_flag); ~CVariableLock(void); public: bool GetLockStatus();//获取资源状态,1——可访问,0——不可访问 private: Lock *m_lock; bool *m_lock_flag; bool m_get_lock_flag; }; // 区域互斥锁构造函数 CVariableLock::CVariableLock(Lock *lock, bool *lock_flag) { m_get_lock_flag = false; if(lock){ m_lock = lock; } else{ m_lock = NULL; } if(lock_flag){ m_lock_flag = lock_flag; } else{ m_lock_flag = NULL; } } // 区域互斥锁析构函数 CVariableLock::~CVariableLock(void) { if(!m_lock || !m_lock_flag){ return; } if(m_get_lock_flag){//只有在获取锁成功情况下才重置变量 WriteLock w_lock(*m_lock); *m_lock_flag = false; } } // 区域互斥锁锁状态成员函数 bool CVariableLock::GetLockStatus(){//获取资源状态,返回结果:1——可访问,0——不可访问 if(!m_lock || !m_lock_flag){ return true; } bool lock_status = true; { { ReadLock w_lock(*m_lock); lock_status = *m_lock_flag; } int count = 50; while(lock_status){ if(count <= 0){ break; } { ReadLock w_lock(*m_lock); lock_status = *m_lock_flag; } count--; Sleep(10);//延时10ms } } bool result = ~(lock_status); if(result){//获取锁成功 { WriteLock w_lock(*m_lock); lock_status = *m_lock_flag;//再次读取变量值 if(lock_status){//已被其他线程锁定 m_get_lock_flag = false; result = false; } else{ m_get_lock_flag = true; *m_lock_flag = true; } } } else{//获取锁失败 m_get_lock_flag = false; } return result; }
变量区域锁工作流程图
使用示例
// 区域互斥锁使用示例 bool lock_flag = false; Lock rw_lock; void Fun1() { CVariableLock lock(&lock_flag, &rw_lock); if(!lock.GetLockStatus()){//获取锁失败 return; } //获取锁成功,锁定区域1 …… } void Fun2() { CVariableLock lock(&lock_flag, &rw_lock); if(!lock.GetLockStatus()){//获取锁失败 return; } //获取锁成功,锁定区域2 …… }
标签:线程锁 type write uniq int image break div variable
原文地址:http://www.cnblogs.com/chenyangchun/p/6892862.html