Search code examples
multithreadingwinapisynchronizationmutual-exclusionread-write

Read/write synchronization


I have a data structure whose operations can be categorized as read operations (e.g. lookup) and write operations (e.g. insertion, removal). These operations should be synchronized so that:

  • Read operations can't execute while a write operation is executing (unless on the same thread), however read operations can be executed concurrently with respect to other read operations.
  • Write operations can't execute while either read or write operations are executing (unless on the same thread).

How can this kind of synchronization be implemented?

The platform is win-api so the api's synchronization objects and interlocked functions are the basic building blocks.


Solution

  • Microsoft's recommended implementation of a Reader/Writer lock is here (you'll have to scroll a bit, to the header "Reader/Writer locks"):

    http://msdn.microsoft.com/en-us/library/ms810427.aspx

    For reference, for those who have the same question but who have the luxury of .NET:

    http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx