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!
It is unsafe for one thread to be reading an array while another thread appends to it.
A thread-safe object is one that always maintains a valid state, as observed by other classes and objects, even in a multithreaded environment.
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
The stdio library is thread-safe if the _mutex_ * functions are implemented. Each individual stream is protected by a lock, so two threads can each open their own stdio stream and use it, without interfering with one another.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With