我有一个全局变量 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/