Sign in to follow this  

thread read/write lock c++/win32threads

This topic is 4687 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I was wondering how you would implement a read/write lock using windows thread synchronization methods (criticalsection,evens,mutex,semaphores). Requirements - there can be more than one read lock - there can only be one write lock - read-lock can only be acquired if write lock is unlocked - write-lock can only be acquired if there are no current read locks Any help, urls and documentation, are appreciated!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
For thread synchronization I generally use CreateEvent to create a waitable event object, then call SetEvent to flag that it is "in use", with other threads checking its state via either, then ResetEvent to flag that it is "not in use".

ie:

HANDLE hEventHandle = CreateEvent(NULL, TRUE, FALSE, NULL);

if(0 == hEventHandle)
{
MessageBox(0, "error", "error", MB_ICONSTOP);
return -1; // or whatever you do to handle errors
}


// to flag as "in use"
SetEvent(hEventHandle);

// do your stuff here

// to flag as "not in use"
ResetEvent(hEventHandle);


// Meanwhile, in your other threads, you then...
WaitForSingleObject(hEventHandle, INFINITE);

// or, if you want to do something in the loop while the event is "in use"
if(WAIT_OBJECT_0 == WaitForSingleObject(hEventHandle, 0))
{
Sleep(0);
}



//Then of course, when all's said and done, release the resource...
CloseHandle(hEventHandle);




Critical Sections are also handy. ie: InitializeCriticalSection / EnterCriticalSection / LeaveCriticalSection / DeleteCriticalSection

Share this post


Link to post
Share on other sites

This topic is 4687 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this