读写锁的实现

读写锁的实现

 

#include " stdafx.h "
#include
< windows.h >
/**/ /*对于一块临界区
**可以同时读
**当要写时,等待所有的读者离开,后来的读者不允许进入
**因为在同一个进程中
**所以使用临界区,而不是使用互斥对象,因为这样比较节省资源
*/

class  __declspec(novtable) auto_RWLock
{
public:
    auto_RWLock(
void);
    
~auto_RWLock(void);

    
void LockForRead(void);
    
void UnLockForRead(void);

    
void LockForWrite(void);
    
void UnLockForWrite(void);

private:
    
long readerCount;
    CRITICAL_SECTION critical_section;
    CRITICAL_SECTION reader_all_leave;
}
;
#include " stdafx.h "
#include
" auto_RWLock.h "

auto_RWLock::auto_RWLock(
void ):readerCount( 0 )
{
    InitializeCriticalSection(
&critical_section);
    InitializeCriticalSection(
&reader_all_leave);
}

auto_RWLock::
~ auto_RWLock( void )
{
    DeleteCriticalSection(
&critical_section);
    DeleteCriticalSection(
&reader_all_leave);
}


void  auto_RWLock::LockForRead( void )
{
    EnterCriticalSection(
&critical_section);
    
    
if(InterlockedIncrement(&readerCount) ==1)
        EnterCriticalSection(
&reader_all_leave);

    LeaveCriticalSection(
&critical_section);
}


void  auto_RWLock::UnLockForRead( void )
{
    
if(InterlockedDecrement(&readerCount)==0)
        LeaveCriticalSection(
&reader_all_leave);
}


void  auto_RWLock::LockForWrite( void )
{
    EnterCriticalSection(
&critical_section);
    EnterCriticalSection(
&reader_all_leave);
}


void  auto_RWLock::UnLockForWrite( void )
{
    LeaveCriticalSection(
&critical_section);
    LeaveCriticalSection(
&reader_all_leave);
}

你可能感兴趣的:(读写锁的实现)