简体   繁体   中英

C++ associative container (unordered_map) find and insert the same key at the same time from multiple threads

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.

  1. 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:

    1. operator[] dynamically create a node containing (empty_value)
    2. bucket pointers point to the newly created (empty_value) node.
    3. the "=" then put "value" in the newly created node.

    find(key) can read garbage after step 2 and before step 3 finishes.

  2. If we use unordered_map::insert, then it will be different, because what happened is:

    1. Node containing (value) is dynamically created.
    2. bucket pointer points to the newly created node.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM