【发布时间】:2016-01-27 14:34:09
【问题描述】:
我有一个全局变量 std::unordered_map themap 。
thread1 执行以下操作:
Time1 :
string s = "user1" ;
themap[s] = 100 ;
Time2 :
string s = "user2" ;
themap[s] = 101 ;
thread2 执行以下操作:
Time2:
string s = "user1" ;
auto got = themap.find( s ) ;
Time1 发生在 Time2 之前,假设在 thread2 中 got != themap.end() 将是正确的, got->second = 100 !!!困扰我的是,如果在 Time2 的那一刻,thread1 正在执行 themap["user2"] = 101 ,这将修改 map 的内存结构,thread2 themap.find 在完全相同的时间执行 find,thread1 修改了 map 的内存内容,如果没有锁,我仍然得到 得到 != themap.end() 吗?并且得到->second = 100 ?
themap["user2"] = 101 得到 = themap.find(s)
同时做会导致got->second不是100?
【问题讨论】:
-
如果这两个线程之间没有同步,那么您就有一个竞争条件并且您的程序表现出未定义的行为。这意味着它可以合法地产生任何结果。
标签: c++ c++11 thread-safety g++ unordered-map