简体   繁体   English

固定大小的stl映射的线程安全

[英]Thread safety of fixed sized stl map

I have a stl map with integer as key and a vector of class object as its value. 我有一个stl映射,其中整数作为键,而类对象的向量作为其值。

class foo {
    // provides wrapper around std::queue for thread safety
    private :
       std::queue<>
}

std::map<unsigned int, std::vector<foo *> > mymap;

foo class is just a thread safe wrapper around std::queue implementation. foo类只是围绕std :: queue实现的线程安全包装器。 Now coming to the actual question - this map is used in a multi threaded scenario where each thread depending upon an arguments passed during creation accesses the corresponding vector. 现在要提出一个实际的问题-该映射用于多线程方案,其中每个线程根据创建过程中传递的参数访问相应的向量。

So lets say i created 4 threads and passed 0,1,2,3 as argument so : 所以可以说我创建了4个线程并传递了0、1、2、3作为参数,因此:

thread 0 - mymap[0];
thread 1 - mymap[1];
thread 2 - mymap[2];
thread 3 - mymap[3];
  1. Size of the map is fixed during creation and is not changed. 地图的大小在创建过程中是固定的,并且不会更改。

Do i need to make my map thread safe ? 我需要确保地图线程安全吗?

  1. as the size of map is fixed so that there will be no re-ordering of the map . 因为地图的大小是固定的,所以不会对地图进行重新排序。
  2. each thread changes only its corresponding vector as per its id. 每个线程仅根据其ID更改其对应的向量。

No, you do not need to add extra synchronization to make this use of std::map thread-safe. 不,您无需添加额外的同步即可使用std::map线程安全。 You are only modifying the map nodes during initialization, and after that you are only reading the map. 您仅在初始化期间修改地图节点,然后再读取地图。 Concurrent reading of the map is no problem, because its structure does not change. 并发读取地图没有问题,因为它的结构不会改变。

The fact that you are modifying the values in the map does not matter, because they don't contribute to the ordering and structure of the map. 您正在修改映射中的的事实并不重要,因为它们不会影响映射的顺序和结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM