I am aware of other similar questions regarding find and insert at the same time, my question is specific to find and insert the SAME KEY at the same time.
Per c++ 14 standard for containers requirements 23.2.5 "15. The insert and emplace members shall not affect the validity of iterators if (N+n) < z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container's bucket count, and z is the container's maximum load factor.".
According to this requirement, if I use unordered_map's reserve method, to pre-allocate buckets, this should take care of most racing conditions. But what if you insert and find the SAME KEY at the same time from multiple threads?
Update: what I really mean is that will find read garbage when inserting at the same time?
I took some time to read the gcc implementation.
If one thread insert using
unordered_map mp; mp[key] = value;
while one thread read using: auto it = mp.find(key); // then use it to access the key-value pair
Then yes, using iterator returned by find() may get garbage, because this is what happened during mp[key] = value:
find(key) can read garbage after step 2 and before step 3 finishes.
If we use unordered_map::insert, then it will be different, because what happened is:
So when using find(key), either unordered_map cannot find the key-value pair, or the key-value pair has been fully created.
This is my understanding to the implementation. please correct me if I am wrong.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.