Basilevs
Basilevs

Reputation: 23896

Locked write, unlocked read

Algorithmic question

How to allow only the following types of threaded operations on an object?

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.

Upvotes: 0

Views: 216

Answers (2)

icecrime
icecrime

Reputation: 76745

You want a "multiple-reader / single-writer" mutex : Boost.Thread provides one.

Upvotes: 1

Steve Townsend
Steve Townsend

Reputation: 54128

Use boost::shared_mutex to handle frequent read, infrequent write access patterns.

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.

Upvotes: 1

Related Questions