The short answer is that it is surprisingly difficult to roll your own read / write lock. It is very easy to miss a very subtle time issue that can lead to a deadlock, two threads that think they have an “exclusive” lock, etc.
In short, you need to keep track of the number of readers at any given time. Only when the number of active readers is zero, should you grant access to stream recording. There are some options for choosing whether readers or writers need priority. (Often you want to give authors a priority based on the assumption that recording is less frequent.) (Surprisingly) the hard part is that no author gets access when there are readers, or vice versa.
There is an excellent MSDN article, “Compound Win32 Synchronization Objects,” which allows you to create read / write locks. It starts simple, and then it becomes increasingly difficult to handle all corner cases. One thing that stood out was that they showed a pattern that looked great - then they will explain why it really doesn't work. If they did not point out problems, you might never have noticed. Well worth a read.
Hope this will be helpful.
Eric Pi
source share