azani
azani

Reputation: 494

Read-write concurrency

I have an object A which contains a bunch of fields that need to be synchronized. I want to enforce the following property:

1) More than one thread can read the object's fields at a time. 2) If at least one thread is reading from the object, the object cannot be modified. 3) If the object is being modified, no thread can read from the object.

In other words, I want a lock such that, any number of readers can hold the lock. But, if any writer holds the lock, nothing else can hold the lock.

How do I do that? I'm using C++, but I expect there should be a language-independent way of doing it.

Upvotes: 1

Views: 369

Answers (1)

jupp0r
jupp0r

Reputation: 4670

The concept you are looking for is a Readers-Writer-Lock. There are C++ implementations out there, most notably one in boost::thread. The idea is that you use a single (logical, often internally implemented using two mutexes) mutex for reading and writing that you can upgrade to require unique locking (when you write) and that multiple readers can lock simultaneously when reading from it.

Upvotes: 1

Related Questions