张氏读写锁,c++信号量实现

ReadWriteLock.h

#pragma once
#include<mutex>
class ReadWriteLock
{
public:
	ReadWriteLock(void);
	~ReadWriteLock(void);
	void LockRead(void);
	void LockWrite(void);
	std::mutex m_lock_writeCount;
	std::mutex m_lock_preWriteCount;
	std::mutex m_lock_readCount;
	int m_readCount;
	int m_writeCount;
	int m_preWriteCount;
	void UnlockRead(void);
	void UnlockWrite(void);
};

ReadWriteLock.cpp

#include "stdafx.h"
#include "ReadWriteLock.h"


ReadWriteLock::ReadWriteLock(void)
	: m_readCount(0), m_writeCount(0)
{
}


ReadWriteLock::~ReadWriteLock(void)
{
}

/*
*张氏读写锁 2015,[email protected] Beijing Normal University
*解决了多线程置换hashmap等操作中,需要线程同步控制的问题
*使用请保留作者信息,以保证程序的正确性
*/
void ReadWriteLock::LockRead(void)
{
Loop:
	while(!m_lock_preWriteCount.try_lock());//锁preWriteCount
	while(!m_lock_writeCount.try_lock());//锁writeCount
	while(!m_lock_readCount.try_lock());//锁readCount
	if(m_preWriteCount>0||m_writeCount>0){//放入唯一一个读进程进入预写与写判断的网关
		m_lock_preWriteCount.unlock();
		m_lock_writeCount.unlock();
		m_lock_readCount.unlock();
		goto Loop;
	}else{//没有写操作也没有预写操作,则允许放入读的进程
		++m_readCount;//读进程加1
		m_lock_preWriteCount.unlock();
		m_lock_writeCount.unlock();
		m_lock_readCount.unlock();
	}
}

void ReadWriteLock::UnlockRead(void)
{
	while(!m_lock_readCount.try_lock());//完成读,则读进程数减一
	--m_readCount;
	m_lock_readCount.unlock();
}




void ReadWriteLock::LockWrite(void)
{
	while(!m_lock_preWriteCount.try_lock());
	++m_preWriteCount;
	m_lock_preWriteCount.unlock();//预写进程加1
Loop:
	while(!m_lock_writeCount.try_lock());
	while(!m_lock_readCount.try_lock());
	if(m_writeCount>0||m_readCount>0){//等待所有已进入预写与写网关的读进程结束,等待写进程结束
		m_lock_writeCount.unlock();
		m_lock_readCount.unlock();
		goto Loop;
	}else{//进入写进程
		m_writeCount=1;//禁止其他写进程和其他读进程进入
		m_lock_writeCount.unlock();
		m_lock_readCount.unlock();
	}//放开写读判断锁
	while(!m_lock_preWriteCount.try_lock());//预写进程减一
	--m_preWriteCount;
	m_lock_preWriteCount.unlock();
}


void ReadWriteLock::UnlockWrite(void)
{
	while(!m_lock_writeCount.try_lock());//写进程置为0,放入预写进程或读进程
	m_writeCount=0;
	m_lock_writeCount.unlock();
}

张氏读写锁,多读操作,单写操作,写操作优先的读写锁。

[email protected] 北京师范大学

2015.12.19

你可能感兴趣的:(张氏读写锁,c++信号量实现)