std::在单独的线程中插入时读取地图

std::map reading while inserting in a separate thread

本文关键字:插入 地图 读取 线程 单独 std      更新时间:2023-10-16

我有这样的地图

map<string,A>

现在,当我从线程 I 遍历映射时,线程 II 正在向其插入一些内容。 这种插入会影响读数吗?

是的,插入会影响读数。该标准不提供线程安全保证。存在竞争条件,它会导致未定义的行为。

是的,它会影响阅读。您需要在这两个线程之间建立额外的同步机制。阅读有关std::mutexstd::unique_lock的信息。

请参阅下面的示例代码:

#include <map>
#include <string>
#include <mutex>
#include <memory>
class MapWithMutex
{
public:
    int readFromMap(const std::string& key)
    {
        std::unique_lock<std::mutex>(mtx);
        //add some check if elements exists
        return myMap[key];
    }
    void insertToMap(const std::string& key, int value)
    {
        //add check if element doesn't already exist
        std::unique_lock<std::mutex>(mtx);
        myMap[key] = value;
    }
private:
    std::map<std::string,int> myMap;
    std::mutex mtx;
};
int main() {
    MapWithMutex thSafeMap;
    //pass thSafeMap object to threads
    return 0;
}

记住使关键部分尽可能小