linux线程同步与互斥-读写锁

时间:2022-11-21 18:34:39

读写锁是一种特殊的自旋锁,对临界资源的访问者分成读者和写者,读者只对临界资源进行读访问,所以可以有好多读者一起读,但此时不能写入,

写者则需要对共享资源进行写操作。相比于其他的所他可以实现读多写少的模型,读者间可以一起读,没有关系,只要维护读者与写者之间互斥即可。

他有三种状态

(1)读加锁 (2)写加锁 (3)不加锁

相关的函数

int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);

//初始化读写锁函数,也可以用宏初始化pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock)  // 成功则返回0,失败则返回错误代码

int pthread_rwlock_rdlock(pthread_rwlock_t *restrict rwlock) ;//读模式加锁,以阻塞方式等待

int pthread_rwlock_wrlock(pthread_rwlock_t *restrict rwlock);//写模式加锁,以阻塞方式等待

int pthread_rwlock_unlock(pthread_rwlock_t *restrick rwlock);//解锁

int pthread_rwlock_tryrdlock(pthread_rwlock_t *restrict rwlock);//读模式加锁,以非阻塞等待

int pthread_rwlock_trywrlock(pthread_rwlock_t *restrict rwlock);//写模式加锁,以非阻塞等待


下面是测试代码


  #include <stdio.h>
  #include <pthread.h>
   
  int book = 0;
  pthread_rwlock_t rwlock;
   
  void *mywrite(void *arg)
  {
      while(1)
      {
          sleep(6);
          if(pthread_rwlock_trywrlock(&rwlock) != 0 )
          {
              printf("I am writer ,reader is reading ...cannot write.\n" );
          }
          else{
          book++;
          sleep(2);
          printf("I an writer, writing book done: %d\n",book );
          pthread_rwlock_unlock(&rwlock);
          }
      }
  }
  
  void *myread(void *arg)
  {
      while(1)
      {
          sleep(2);
          if(pthread_rwlock_tryrdlock(&rwlock) != 0 ){
          printf("I am reader , writer is writing ...cannot read. \n" );
          }
          else{
             sleep(2);
             printf("I am reader ,reading the book is:%d\n",book );
              pthread_rwlock_unlock(&rwlock);

      }
      }
  }
  
  
  int main()
  {   pthread_rwlock_init(&rwlock,NULL);
      pthread_t r,w;
      pthread_create(&r,NULL,myread,NULL);
      pthread_create(&w,NULL,mywrite,NULL);
  
  
      pthread_join(r,NULL);
      pthread_join(w,NULL);
      pthread_rwlock_destroy;
      return 0;
  }

运行结果有序的读写,两种关系之间互斥。
  linux线程同步与互斥-读写锁