如果不同的线程始终使用不同的键,是否可以将它们插入到映射中? [英] Can different threads insert into a map if they always use different keys?

查看:63
本文介绍了如果不同的线程始终使用不同的键,是否可以将它们插入到映射中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为对象设计消息队列.有一组X线程可以全部向该对象发送消息(待稍后处理).如果我有std::map<thread_id_t, message>,则此线程安全吗,假设线程1仅将密钥为1的消息添加到密钥2,将线程2的消息添加为密钥2,等等.?

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..?

推荐答案

std::map对于多个同时写入的线程而言不是线程安全的.

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

STL映射不是线程安全的许多原因之一是,STL映射的基础实现是AVL树,需要在多次插入后每隔一段时间重新平衡一次.重新平衡地图会影响多个节点,并且绝对不是线程安全的.

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.

请参阅优秀的博士. Dobb关于无锁数据结构的文章,如果这对您来说听起来很有趣.

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

这篇关于如果不同的线程始终使用不同的键,是否可以将它们插入到映射中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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