C ++线程安全的对象 [英] C++ Thread-Safe Object

查看:112
本文介绍了C ++线程安全的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个令人难以置信的简单的问题,但在我所有的研究,我一直没能找到一个明显的例子...

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

我试图建立与getter和setter函数访问私有变量的自定义类。本课程将再次在全球范围内(EXTERN)被实例化,并将作为我的应用程序的数据缓存。它将由多个线程同时使用,99%的阅读,和速度是非常重要的。有没有什么办法可以让并发读取,只是写锁? (我假设没有)

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)

我只是包括范围互斥的getter和setter的第一行?不然怎么设计这个看似简单的目标的最佳途径?任何实例或链接会大大AP preciated(我有一个很难包装我的头周围)。

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.

我真的AP preciate呢!

I really appreciate it!

推荐答案

假设你的封装是否正确,对getter和setter方法​​的锁应该是足够了。

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

要提供并发读取,看看读者 - 写锁,这pcisely提供$ P $同步你想要的水平。我认为,<一个href=\"http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex\"><$c$c>boost::shared_mutex符合本条例草案。

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.

由于这是一个缓存,如果你能够忍受过时的价值观,它可能是值得的你,在性能方面,调查的 RCU ,或只读副本更新。有至少一个库用户空间RCU。

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.

这篇关于C ++线程安全的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆