c++实现简单的读写锁

#include
#include 
#include
class RWLock{ // 读写锁
  public:   
   RWLock();
  ~RWLock();

   void read_lock();
   void read_unlock();

   void write_lock();
   void write_unlock();   

  private:
    pthread_mutex_t write_m_; 
    pthread_mutex_t count_m_; 
    int count_; 
}


RWLock::RWLock():count_(0){
  pthread_mutex_init(&write_m_,NULL);
  pthread_mutex_init(&count_m_,NULL);  
}

RWLock::~RWLock(){
  pthread_mutex_destory(&write_m_);
  phtread_mutex_destory(&count_m_);         
}

void RWLock::read_lock(){
  pthread_mutex_lock(&count_m_);    
  if(count_==0){
    pthread_mutex_lock(&write_m_);   
  }             
  ++count_;     
  pthread_mutex_unlock(&count_m_);              
}

void RWLock::read_unlock(){
  pthread_mutex_lock(&count_m_);
  --count_;
  if(count_==0){
    pthread_mutex_unlock(&write_m_);    
  }  
  pthread_mutex_unlock(&count_m_);      
}

void RWLock::write_lock(){
  pthread_mutex_lock(&write_m_);        
}

void RWLock::write_unlock(){
  pthread_unlock(&write_m_);        
}

你可能感兴趣的:(操作系统课件)