STL容器的只读操作
这里需要建议:STL 容器的哪些操作被视为只读?以vector
为例,是否可以肯定地说,任何不改变底层int数据的操作都是只读的?我正在编写一个多线程程序,但不太确定通过引用/指针传递容器是否是线程安全的。
两者之间,相同的规则也适用于 basic_string 吗?有没有推荐的资源可以帮助快速了解STL容器的内部机制?谢谢。
Need advice here: which of the STL container's operations are considered read-only? Take vector<int>
as example, would it be safe to say that any operation that does not alter the underlying int data is read-only? I am writing a multi-threaded program, but not too sure if it is thread-safe to pass container by reference/pointer.
Between, will the same rules apply to basic_string as well? Any recommended resource that helps for quickly gaining understanding on internal mechanism of STL container? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在多线程线程环境下操作stl容器时使用pthread读写锁。他们效率很高。 pthread读写锁参考:
Pthread读写锁-Yolinux
Use pthread read-write locks in multi-threading threading environment while operating on stl containers. They are quite efficient. Reference for pthread read -write locks:
Pthread Read Write Locks - Yolinux
标准中唯一提到的是
The only thing which is mentioned in standard is
声明为 const 的方法很可能不会修改容器,尽管您不能确定。
在多线程应用程序中使用 STL 容器时,您将需要外部同步机制。 C++ 标准库不是线程安全的,假设其中一个线程更改了向量对象的状态,任何没有同步的多线程使用都会导致未定义的行为。
Methods declared const most likely won’t modify the container, although you can’t be sure.
When using STL containers in a multithreaded application you will need an external synchronization mechanism. The C++ standard library is not thread safe, and any use from multiple threads without synchronization will result in undefined behavior, assuming that one of the threads change the state of the vector object.
顺便说一句,该标准没有提及容器的安全性。但是用
const
标记的方法保证不会修改容器。*如果线程将同时读取和写入数据,则需要同步它们。
**逻辑上修改,即。虽然我不知道任何容器,但任何可变成员都可以在 const 方法中更改。*
The Standard says nothing on the safety of containers, by the way. But a method marked with
const
is guaranteed to not modify the container.*If thread's will be reading and writing to the data at the same time, you'll need to synchronize them.
**Logically modify, that is. Though I don't know any containers off-hand, any mutable members can change in const methods.*