stl映射查找线程安全
stl map 上的 find 调用线程安全吗?
Is find call on stl map thread safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
stl map 上的 find 调用线程安全吗?
Is find call on stl map thread safe?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
不,C++ 规范不保证规范中对任何 STL 容器上的操作的线程安全性。如果线程安全很重要,那么您应该提供自己的锁定。
话虽这么说,不同的实现似乎提供了不同的保证。例如,大多数似乎允许多个并发读取器,只要没有同时执行写入即可。如果您不关心可移植性,您可以研究您的实现文档。例如,来自此处的 SGI STL:
从这个答案来看,类似的保证似乎是由 Dinkumware 制作(他们制作了 Microsoft 的 STL 实现)。
No, the C++ spec makes no guarantees on thread safety in the spec for operations on any STL containers. If thread safety is important, the you should provide your own locking.
That being said, different implementations seem to offer different guarantees. Most seem to allow multiple concurrent readers, for example, as long as no writing is being performed concurrently. If you don't care about portability, you can research the documentation for your implementation. For example from here for SGI STL:
From this answer, a similar guarantee seems to be made by Dinkumware (they make Microsoft's STL implementation).
否:当另一个线程与您的
查找
同时更新地图时,行为是未定义的。No: when another thread is updating the map concurrently with your
find
, behavior is undefined.我试图找到问题的答案。
https://gcc.gnu.org/onlinedocs /libstdc++/libstdc++-html-USERS-3.4/stl__map_8h-source.html
可以看到stl地图源。
搜索
find()
。发现于497行、524行。代码写为_M_t.find(__x);
然后搜索
_M_t
。它位于 124 行。
它被写为
_Rep_type _M_t;
如果属性
_M_t
是为每个线程创建的,它可能是线程安全的。但我不这么认为。
如果 2 个线程同时使用
find
,它们将同时使用_M_t
。_Rep_type
连接到_Rb_tree
。您可以在下面的源代码中看到
_Rb_tree
。https://gcc.gnu.org/onlinedocs /libstdc++/libstdc++-html-USERS-4.1/stl__tree_8h-source.html
find()
进行树旅行(见下面的代码)。__x
和__y
会发生意外的变化。I tried to find the answer to the question.
https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-3.4/stl__map_8h-source.html
you can see stl map souce.
search
find()
. It is found in 497 line, 524 line. Code is written as_M_t.find(__x);
Then search
_M_t
.It is found in 124 line.
It is written as
_Rep_type _M_t;
If property
_M_t
is created per thread, It could be thread safe.But I don't think so.
If 2 thread use
find
concurrently, they would use_M_t
concurrently._Rep_type
is connected to_Rb_tree
.You can see
_Rb_tree
in below source.https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.1/stl__tree_8h-source.html
find()
do tree travel(see below code).unwilled change in
__x
and__y
would occur.实际上,Microsoft Visual Studio 2008 附带的 STL 似乎对修改映射的操作有一些锁定(我假设它对于 set 是相同的)。这是相当烦人的,因为我正在多个线程中构建更多地图,这会影响我的性能。
Actually, the STL shipped with Microsoft Visual Studio 2008 seems to have some locks on operations that modify the map (and i assume it is the same for set). It is rather annoying, as i'm building more maps in multiple threads and it is killing my performance.