zoukankan      html  css  js  c++  java
  • 仅使用互斥锁实现读写锁

    清楚认识到读写锁分为共享锁(读锁)和独占锁(写锁),可能通过设置标志位记录读锁调用的次数结合互斥锁实现共享锁。但需要注意的是,以下的实现在多个写锁被阻塞时非常消耗计算机资源。因为线程阻塞在写锁中而没有被投入睡眠,导致轮询策略。避免轮询可通过互斥锁+条件变量实现读写锁,具体实现见上一篇博文。
    以下是代码实现:

    #include<pthread.h>
     
    pthread_mutex_t rdLock = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_t wrLock = PTHREAD_MUTEX_INITIALIZER;
    int readCnt = 0;//设置读锁调用次数的标志位
     
    //实现读锁(共享锁)
    void rdLock() {
    	pthread_mutex_lock(&rdLock);
    	readCnt++;
    	if (readCnt == 1)//有人读,于是阻塞写锁
    		pthread_mutex_lock(&wrLock);
    	pthread_mutex_unlock(&rdLock);
    }
     
    void rdUnlock() {
    	pthread_mutex_lock(&rdLock);
    	readCnt--;
    	if (readCnt == 0)//表示已没有人在读,释放写锁,可以写入了
    		pthread_mutex_unlock(&wrLock);
    	pthread_mutex_unlock(&rdLock);
    }
     
    void wrLock() {
    	pthread_mutex_lock(&wrLcok);
    }
     
    void wrUnlock() {
    	pthread_mutex_unlock(&wrLock);
    }
    
  • 相关阅读:
    WordCount的程序设计没写出来怎么办
    小程序分析
    程序单元测试
    Visual studio 2013安装
    四则运算源代码
    在VC环境下执行代码出现错误
    微点评微信软件
    软件工程学习
    查找抄袭文章
    软件附加题简答
  • 原文地址:https://www.cnblogs.com/wsl-hitsz/p/15185464.html
Copyright © 2011-2022 走看看