简体   繁体   中英

C++ Thread-Safe Object

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM