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!

Harry
  • 863
  • 3
  • 10
  • 26
  • 2
    It's anything but simple. Every single detail is important. Unfortunately your description has precious little of those. – n. m. could be an AI Mar 18 '14 at 22:22
  • You can protect accessing class members using a [`std::mutex`](http://en.cppreference.com/w/cpp/thread/mutex) or similar synchronization mechanism, but maybe for `const` getter methods, the asynchronous lock variable needs to be declared `mutable`. – πάντα ῥεῖ Mar 18 '14 at 22:22

1 Answers1

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.

Matthew G.
  • 1,298
  • 10
  • 24
  • shared_mutex is exactly what I was looking for - thanks! I ended implementing a solution very similar to: http://stackoverflow.com/a/6450576/455215 – Harry Mar 20 '14 at 14:51