gpt4 book ai didi

c++ - STL映射查找线程安全

转载 作者:IT老高 更新时间:2023-10-28 23:14:19 24 4
gpt4 key购买 nike

STL map 线程上的 find 调用安全吗?

最佳答案

不,C++ 规范不保证任何 STL 容器上操作的规范中的线程安全。如果线程安全很重要,您应该提供自己的锁定。

话虽如此,不同的实现似乎提供了不同的保证。例如,大多数似乎允许多个并发读取器,只要没有同时执行写入。如果您不关心可移植性,则可以研究实现文档。例如来自 here对于 SGI STL:

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

来自 this answer ,Dinkumware 似乎也做出了类似的保证(他们实现了微软的 STL 实现)。

Multiple threads can safely read the same container object. (There are nunprotected mutable subobjects within a container object.)

Two threads can safely manipulate different container objects of the same type. (There are no unprotected shared static objects within a container type.)

You must protect against simultaneous access to a container object if at least one thread is modifying the object. (The obvious synchronization primitives, such as those in the Dinkum Threads Library, will not be subverted by the container object.)

关于c++ - STL映射查找线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5912539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com