Can different threads insert into a map if they always use different keys?

空扰寡人 提交于 2019-12-24 01:29:06

问题


I'm trying to design a message queue for an object. There is a set of X threads that can all send message (to be processed later) to this object. If I have a std::map<thread_id_t, message>, is this thread safe, assuming thread one only adds messages with a key of 1, thread 2 to key 2, etc..?


回答1:


std::map is not thread safe for multiple simultaneous writers.

One of the many reasons why STL maps are not thread safe is that the underlying implementation of an STL map is an AVL tree that needs to be rebalanced every once in a while after a number of insertions. Rebalancing the map affects multiple nodes and is definitely not thread safe.

Refer to the excellent Dr. Dobb's article on lock-free data structures if any of this sounds interesting to you.




回答2:


The general rule for classes in the standard C++ library is this: if you call a non-const method on an object (with the exception of some methods like std::vector<T>::operator[]()) you cannot have any other thread accessing this object in any way concurrently. If you need to use the operations you need to make synchronize the accesses between the different threads somehow. The relevant clauses in the standard are 17.6.4.10 [res.on.objects] paragraph 1:

The behavior of a program is undefined if calls to standard library functions from different threads may introduce a data race. The conditions under which this may occur are specified in 17.6.5.9.

... and 17.6.5.9 [res.on.data.races] which describes that the standard C++ library isn't allowed to do mutate objects except when a non-const member function is called on them.

Since inserting an object into a std::map<...> is clearly a non-const operations, you cannot do it concurrently from multiple threads without synchronization.



来源:https://stackoverflow.com/questions/27829806/can-different-threads-insert-into-a-map-if-they-always-use-different-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!