简体   繁体   English

C ++线程安全对象

[英]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. 我正在尝试使用getter和setter函数构建一个可以访问私有变量的自定义类。 This class will be instantiated once in the global scope (extern) and will serve as a data cache in my application. 此类将在全局范围(extern)中实例化一次,并将在我的应用程序中用作数据缓存。 It will be used by many threads simultaneously, 99% for reading, and speed is extremely important. 它将被许多线程同时使用,99%用于读取,速度非常重要。 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? 我是否只是将一个范围的互斥锁作为getter和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. 我确实编译了Boost,所以它可以使用。

I really appreciate it! 我真的很感激!

Assuming your encapsulation is correct, locks on the getter and setters should be sufficient. 假设您的封装是正确的,那么getter和setter上的锁就足够了。

To provide concurrent reads, look into Readers-Writer locks, which provides precisely the level of synchronization you desire. 要提供并发读取,请查看Readers-Writer锁定,它可以精确地提供所需的同步级别。 I think boost::shared_mutex fits the bill. 我认为boost::shared_mutex符合要求。

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. 由于这是一个缓存,如果您能够容忍过时的值,那么就性能而言,调查RCU或读取复制更新可能是值得的。 There's at least one library for user-space RCU. 用户空间RCU至少有一个库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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