STL容器的只读操作

发布于 2024-08-13 00:24:05 字数 202 浏览 3 评论 0原文

这里需要建议: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寒尘 2024-08-20 00:24:06

在多线程线程环境下操作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

聚集的泪 2024-08-20 00:24:06

标准中唯一提到的是

  • 多个读取器是线程安全的(duhhhhhh)
  • 不同容器的多个写入器是线程安全的(再次duhh...但较小的一个:)这意味着没有实现可以对其静态成员进行修改损害线程安全

The only thing which is mentioned in standard is

  • Multiple readers are thread safe (duhhhhhh)
  • Multiple writers to different containers are thread safe(again duhh...but a smaller one :) this means that no implementation can have static members modification of which can compromise thread safety
離人涙 2024-08-20 00:24:05

声明为 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.

薄暮涼年 2024-08-20 00:24:05

顺便说一句,该标准没有提及容器的安全性。但是用 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.*

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文