C++实现读写锁ReadWriteLock

C++实现读写锁ReadWriteLock

  • 描述
  • 使用示例
  • 源码
    • ReadWriteLock.h

描述

1)读写锁基本思想:写者之间互斥、写者和读者之间互斥,而读者之间并不需要互斥
2)读写锁分为两种:读者优先和写者优先;
读者优先,即当前只要可读,就是可进入的;
写者优先,读者需要看看当前是否有写者要读,如果有,则等待至没有写者正在写或者需要写的情况;
注:两种方式,都会存在饥饿现象;

使用示例

#include"ReadWriteLock.h"
#include
#include
#include
using namespace std;

//写者优先
ReadWriteLock readWriteLock(true);

void reader() {
	readWriteLock.readLock();
	cout << "reader" << endl;
	this_thread::sleep_for(std::chrono::seconds(3));
	readWriteLock.readUnLock();
}

void writer() {
	readWriteLock.writeLock();
	cout << "writer" << endl;
	this_thread::sleep_for(std::chrono::seconds(3));
	readWriteLock.writeUnLock();
}

int main() {
	vector<thread>vec;
	for (int i = 0; i < 5; ++i) {
		vec.push_back(thread(reader));
		vec.push_back(thread(writer));
	}
	for (int i = 0; i < vec.size(); ++i) {
		if(vec[i].joinable())
			vec[i].join();
	}
}

源码

ReadWriteLock.h

#pragma once
#include
#include

class ReadWriteLock {
private:
	int readWaiting = 0;  //等待读
	int writeWaiting = 0; //等待写
	int reading = 0; //正在读
	int writing = 0;  //正在写
	std::mutex mx;
	std::condition_variable cond;
	bool preferWriter;  //偏向读
public:
	ReadWriteLock(bool isPreferWriter = false) :preferWriter(isPreferWriter) {}

	void readLock() {
		std::unique_lock<std::mutex>lock(mx);
		++readWaiting;
		cond.wait(lock, [&]() {return writing <= 0 && (!preferWriter || writeWaiting <= 0); });
		++reading;
		--readWaiting;
	}

	void writeLock() {
		std::unique_lock<std::mutex>lock(mx);
		++writeWaiting;
		cond.wait(lock, [&]() {return reading <= 0 && writing <= 0; });
		++writing;
		--writeWaiting;
	}

	void readUnLock() {
		std::unique_lock<std::mutex>lock(mx);
		--reading;
		//当前没有读者时,唤醒一个写者
		if(reading<=0)
			cond.notify_one();  
	}

	void writeUnLock() {
		std::unique_lock<std::mutex>lock(mx);
		--writing;
		//唤醒所有读者、写者
		cond.notify_all(); 
	}
};

你可能感兴趣的:(C++技术,sync,c++11,thread,多线程)