首页 > 解决方案 > 在读取地图成员时调用 unordered_map::operator[] 是否安全?

问题描述

我知道我可能无法同时从多个线程访问operator[]std::unordered_map

但是,假设我用互斥锁包围operator[]调用本身,而访问元素本身仍然是并发的:

我是否允许通过指针读取/写入地图的元素,同时另一个线程正在调用operator[]

例如:

    // This code will run concurrently from multiple threads

    Thing* thing = nullptr;
    {
        std::lock_guard<std::mutex> lock(my_mutex);
        thing = &my_map[thread_id];
    }

    // This may happen at the same time operator[] is called
    thing->value += 10;

这安全吗?

或者,例如:可能operator[]会在内存中移动东西,从而使当前Thing*由不同线程持有的指针无效?

标签: c++concurrencyc++-standard-library

解决方案


std::unordered_map/operator[],强调我的:

如果发生插入并导致容器重新散列,则所有迭代器都将失效。否则迭代器不受影响。引用不会失效

所以你很好。


推荐阅读