std :: map从多个线程写入/读取 [英] std::map write/read from multiple threads

查看:187
本文介绍了std :: map从多个线程写入/读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从多个线程读写std :: map。



如果没有互斥锁,是否可以做到这一点?



如果没有,在C ++ 11中最简单的方法是什么? / p>

解决方案

如果 std :: atomic<> ,您可以从任意线程中修改和读取它们,但是您需要以某种方式保存它们的地址-指针,引用或迭代器-并且您不需要其他任何知识线程将对其调用擦除...。



仍然,即使原子值也不能保证安全修改容器(例如,插入或擦除元素),而其他线程也在做修改,查找或迭代。甚至 const 函数-如 size() empty() begin() end() count()和迭代器移动-是不安全的,因为变异操作可能正在重新连接节点间链接或更新相同数据的过程中。



对于上述以外的任何内容,您将需要一个互斥体。






举一个具体的例子,说您插入的节点具有 std :: string client_counter -您可以启动一个线程获取对该元素的迭代器并对该计数器进行原子更新,而其他线程可以查找该元素并从中读取,但不能擦除。您仍然可以将其他节点以及其他更新程序和读取器插入映射,而无需与 client_counter 进行任何额外的同步。更新线程。


I want to be able to read and write in a std::map from multiple threads. Is there a way to do that without mutex (maybe with std::atomic)?

If not, what's the simplest way to do that in C++11?

解决方案

If the values are std::atomic<>, you can modify and read them from arbitrary threads, but you'll need to have saved their addresses somehow - pointers, references or iterators - and you'll need to know no other thread will call erase on them....

Still, even atomic values won't make it safe to modify the container (e.g. inserting or erasing elements), while other threads are also doing modifications or lookups or iteration. Even the "const" functions - like size(), empty(), begin(), end(), count(), and iterator movement - are unsafe, because the mutating operations may be in the middle of rewiring the inter-node links or updating the same data.

For anything more than the above, you will need a mutex.


For a concrete example, say you've inserted a node with std::string key "client_counter" - you could start a thread that gets an iterator to that element and does atomic updates to the counter, while other threads can find the element and read from it but must not erase it. You could still have other nodes inserted in the map, with other updaters and readers, without any extra synchronisation with the client_counter-updating thread.

这篇关于std :: map从多个线程写入/读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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