TCP专题

#include<iostream>
#include<pthread.h>
#include<stddef.h>
class RWClock{
  public:   
    RWClock(int priority);
    ~RWClock();
    void ReadLock();
    void ReadUnLock();  
    void WriteLock();
    void WriteUnLock();
  private:
     //no copying allowed;
     RWClock(const RWClock&); 
     RWClock& operator=(const RWClock&);
     //priority operation();
     void ReadLockOfPriority();
     void ReadUnLockOfPriority();   
     void WriteLockOfPriority();
     void WriteUnLockOfPriority();

     pthread_mutex_t write_mu_;
     pthread_mutex_t count_mu_;
     pthread_mutex_t queue_mu_;
     int count_;
     int priority_;  // 0 or 1;代表读写不同优先级;
}

RWClock::RWClock(int priority):witte_mu_(pthread_mutex_int(&write_mu_,NULL)),
                   count_mu_(pthread_mutex_int(&count_mu_,NULL)), 
                   queue_mu_(pthread_mutex_int(&queue_mu_,NULL)),
                   count_(0),
                   priority_(priority){}

RWClock::~RWClock(){
  pthread_mutex_destory(&write_mu_);    
  pthread_mutex_destory(&count_mu_);        
  pthread_mutex_destory(&queue_mu_);        
}
//read lock priority;
//queue when get the lock;
void RWClock::ReadLockOfPriority(){
  if(priority_ == 0){
    pthread_mutex_lock(&count_mu_);
    if(count_ == 0){
      pthread_mutex_lock(&write_mu_);  
    }
    ++count_;
    pthread_mutex_unlock(&count_mu_);         
  }
  else{
    //where to put queue; //位置的放置和api的使用搭上关系; 
    pthread_mutex_lock(&queue_mu_); //等待资源时 后面全部阻塞在这个锁上面;
    pthread_mutex_lock(&count_mu_);
    if(count_ == 0){
     // pthread_mutex_lock(&queue_mu_);
      pthread_mutex_lock(&write_mu_);  
    }
    ++count_;
    pthread_mutex_unlock(&count_mu_);  
    pthread_mutex_unlock(&queue_mu_);   
  }     
}

void RWClock::ReadUnLockOfPriority(){
  pthread_mutex_lock(&count_mu_);
  --count_;
  //only if there doest exists read thread;
  if(count_ == 0){
    pthread_mutex_unlock(&write_mu_);  
  }
  pthread_mutex_unlock(&count_mu_);     
}

void RWClock::WritelockOfPriority(){
  if(priority_ == 0){//读优先级;
    pthread_mutex_lock(&queue_mu_);   
    pthread_mutex_lock(&wirte_mu_);   
    //pthread_mutex_unlock(&queue_mu_); 
  }  
  else{
    pthread_mutex_lock(&wirte_mu_);   
  }
}

void RWClock::WriteUnlockOfPriority(){
  if(priority_ == 0){//读优先级; 
    pthread_mutex_unlock(&wirte_mu_);     
    pthread_mutex_unlock(&queue_mu_);   
    //pthread_mutex_unlock(&queue_mu_); 
  }  
  else{
    pthread_mutex_unlock(&wirte_mu_);     
  }
}

//read lock;
void RWClock::ReadLock(){
  ReadLockOfPriority();
}
//read unlock;
void RWClock::ReadUnlock(){
  ReadUnLockOfPriority();   
}
//write lock;
void RWClock::WriteLock(){
  WritelockOfPriority();
}
//write unlock;
void RWClock::WriteUnlock(){
  WriteUnlockOfPriority();
}
点赞