3

I am newbie to c++ multithreading programming. I read some documents and some articles from web and notice the fact that multi find operation at the same time in STL unordered_map are allowed, while multi insert operation are not allowed.

I have two questions:

  1. Could find operation and insert operation at the same time be allowed? For example,

    std::string x = "jim";
    std::string y = "marry";
    std::unordered_map<std::string, int> map;  
    // Thead A executes below code 
    auto iterator = map.find(x);   
    // Thread B executes below code
    map.insert(std::make_pair(y, "value"));
    

    Please notice here x and y are not the same.

  2. What if x and y are the same? What would happen if we find the key and insert the same key in the meanwhile?

Thanks guys if you answer this question with the reference where you get this knowledge.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Dimen61
  • 78
  • 6
  • 3
    for standard containers, only [concurrent const access is thread-safe](https://en.cppreference.com/w/cpp/container#Thread_safety) – kmdreko Oct 11 '18 at 09:06
  • [link](https://stackoverflow.com/questions/9685486/unordered-map-thread-safety)Lalaland's answer actually solves my questions. But before I proposed this question, I can't sure the rightness of rules from his answer because of the absence of reference. @kmdredo offers the reference eliminating my doubt. Thanks guys who pay attention to this question:) – Dimen61 Oct 12 '18 at 08:19

2 Answers2

1

Standard containers are not thread-safe. So you need to wrap your unordered_map into the class and expose thread-safe functions to insert and find items, for example using a mutex.

Here is some pseudo-code:

class my_map
{
private:
    static std::mutex my_mutex;
    typedef map<std::string, int> my_map;
    std::unordered_map my_map;
public:
    void insert(...)
    {
        my_mutex.lock();
        map.insert(...);
        my_mutex.unlock(); // still not safe in case of exception
    }
    my_map::iterator find(...)
    {
        my_mutex.lock();
        var result = map.find(...);
        my_mutex.unlock();
        return result;
    }
}
serge
  • 992
  • 5
  • 8
1

Answer for both: Due to the rules of the C++ memory model such a data race leads to undefined behaviour. So anything could happen. You must guarantee thead-safe operations and should add a std::mutex e.g. (https://en.cppreference.com/w/cpp/thread/mutex)

OpusV
  • 23
  • 6