Home > other >  Can I call these member functions of std::unordered_map concurrently?
Can I call these member functions of std::unordered_map concurrently?

Time:10-26

I have a global std::unordered_map<int, int> m. I also have exactly one thread that is type A and multiple threads are type B running concurrently.

Thread type A: call insert(), erase() to add/remove some elements (guarantee not the elements read/write in the thread type B concurrently) of m

Thread type B: call operator[] of m, do something like m[key] = value. (guarantee thread type B will not modify the same element concurrently, and the key exists in m already)

Is it safe to do these operations concurrently without a lock?

CodePudding user response:

No. insert can rehash the array which reallocates the bucket array. If that happens right before operator[] accesses it, that's a use-after-free.

This probably isn't the only reason it's unsafe, but we only have to find one, to prove that it's unsafe.

CodePudding user response:

No, it is not safe. None of the methods of std::unordered_map, nor any other container in the C library, are thread safe. Therefore if one execution thread is modifying the container, all access to the container, from all execution threads, must be properly synchronized.

  • Related