c++ - unordered_map find() 和 operator []

标签 c++ c++11 thread-safety g++ unordered-map

我有一个全局变量 std::unordered_map < std::string,int > themap 。

线程 1 执行以下操作:

Time1 : 
string s = "user1" ; 
themap[s] = 100 ;

Time2 :
string s = "user2" ;
themap[s] = 101 ;

线程 2 执行以下操作:

Time2:
string s = "user1" ;
auto got = themap.find( s ) ;

Time1 发生在 Time2 之前,假设在 thread2 中, got != themap.end() 将是正确的并且 got->second = 100 !!!令我困扰的是,如果在 Time2 的那一刻,thread1 正在执行 themap["user2"] = 101,这将修改 themap 的内存结构,thread2 themap.find 在同一时间执行 find thread1 修改 themap 的内存内容,如果没有锁,我还是明白了 得到 != themap.end() 了吗?得到->second = 100 ?

themap["user2"] = 101 并得到 = themap.find( s )
同时做会导致 got->second not to 100 ?

最佳答案

unordered_map thread safe 是真的一个线程写,多个线程读。

此外,在时间 1 的示例中,您正在修改 "user1",然后在时间 2 的线程 2 中搜索它。您在时间 2 的线程 1 中设置 "user2"的事实是正交的。

关于被修改的内部存储器,这不是问题,因为在您插入新值时 find 使用的迭代器会启动 will not be invalidated .

因此在您的测试用例中没有竞争条件。

关于c++ - unordered_map find() 和 operator [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380557/

相关文章:

c++ - 为什么 lambda 只捕获自动存储变量?

c++ - 如果只有属性的成员函数是 noexcept,如何声明 noexcept?

c++ - 如何为按需构造其值的迭代器实现 operator->?

c++ - 命名参数习语和(抽象)基类

c++ - 匿名 std::packaged_task

c++ - 如何让我的程序监视 C++ 中的文件修改?

c++ - 如何防止 Box2D 中传感器对象上的隧道效应

multithreading - 编译时 -pthread 和 -lpthread 之间的区别

c++ - 运算符 >> 不喜欢 vector<bool>?

c - 这个函数是完全线程安全的吗?