Locked write, unlocked read
How to allow only the following types of threaded operations on an object?
- multiple simultaneous reads, no writes
- single write, no reads
Example: wrapper for STL container allowing efficient search from multiple threads. For simplicity, let assume no iterator can be accessed from outside of the wrapper in question.
Let's assume we have semaphores and mutexes at out disposal.
I know that boost libraries has this concept implemented. I'd like to understand how is this usually done.
As you've noted, STL containers are 'leaky' in that you can retrieve an iterator which has to be treated as either an implicit ongoing operation for write (if non-const) or read (if const), until the iterator goes out of scope. Writes to the container by other threads while you hold such an iterator can invalidate it. Your wrapper would have to be carefully designed to handle this case and keep the wrapper class efficient.
You want a "multiple-reader / single-writer" mutex :