6

This might seem like an incredibly simple question, but in all my research I haven't been able to find a clear example...

I'm trying to build a custom class with private variables accessible with getter and setter functions. This class will be instantiated once in the global scope (extern) and will serve as a data cache in my application. It will be used by many threads simultaneously, 99% for reading, and speed is extremely important. Is there any way to allow concurrent reads and just lock for writing? (I'm assuming not)

Do I simply include a scoped mutex as the first line of the getter and setter? Or how is the best way to design this seemingly simple object? Any examples or links would be greatly appreciated (I'm having a hard time wrapping my head around it).

I do have Boost compiled in, so it's usable.

I really appreciate it!

2
  • 2
    It's anything but simple. Every single detail is important. Unfortunately your description has precious little of those. Mar 18, 2014 at 22:22
  • You can protect accessing class members using a std::mutex or similar synchronization mechanism, but maybe for const getter methods, the asynchronous lock variable needs to be declared mutable. Mar 18, 2014 at 22:22

1 Answer 1

9

Assuming your encapsulation is correct, locks on the getter and setters should be sufficient.

To provide concurrent reads, look into Readers-Writer locks, which provides precisely the level of synchronization you desire. I think boost::shared_mutex fits the bill.

Since this is a cache, if you are able to tolerate out of date values, it may be worth it for you, in terms of performance, to investigate RCU, or Read-copy-update. There's at least one library for user-space RCU.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.