Readers/writers Lock Data structure:
Readwrit's Initrwlock ()
BOOL Initrwlock (RWLock *plock)
{
Plock->nreadercount = 0;
Plock->hdatalock = CreateSemaphore (null, 1, 1, NULL);
if (Plock->hdatalock = = NULL)
return FALSE;
Plock->hmutex = CreateMutex (null, FALSE, NULL);
if (Plock->hmutex = = NULL)
{
CloseHandle (Plock->hdatalock);
return FALSE;
}
return TRUE;
}
The next question is how to add the error handling function to produce a function called Mywaitforsingleobject (), as follows:
BOOL Mywaitforsingleobject (HANDLE hobject)
{
int result;
result = WaitForSingleObject (hobject, maximum_timeout);
Comment this off if you want this to be non-fatal
if (Result! = WAIT_OBJECT_0)
FatalError ("Mywaitforsingleobject-"
"Wait failed,you probably forgot to call release!");
return (Result = = WAIT_OBJECT_0);
}
Readwrit's Readok () and Writeok ()
BOOL Readok (RWLock *plock)
{
This check was not perfect,because we
Do not know for sure if we is one of this readers
Return (Plock->nreadercount > 0);
}
BOOL Writeok (RWLock *plock)
{
DWORD result;
The first reader may is waiting in the mutex
But a more than that's an error
if (Plock->nreadercount > 1)
return FALSE;
This check isn't perfect,because we do not know
For sure if this thread is the one that hand the
Semaphore locked.
result = WaitForSingleObject (plock->hdatalock, 0);
if (result = = Wait_timeout)
return TRUE;
A count is Kept,which were incremented in Wait
result = ReleaseSemaphore (plock->hdatalock,1,null);
if (result = = FALSE)
FatalError ("Writeok-releasesemaphore failed");
return FALSE;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Readers/writers Lock