I have a map like this
map<string,A>
Now when I am iterating through the map from thread I, thread II is inserting something on to it. Will this insertion affect the reading ?
I have a map like this
map<string,A>
Now when I am iterating through the map from thread I, thread II is inserting something on to it. Will this insertion affect the reading ?
Yes, the insert can affect the reading. The standard does not provide a thread safety guarantee. There is a race condition, and it leads to undefined behaviour.
Yes it will affect the reading. You need additional synchronization mechanism between those two threads. Read about std::mutex
and std::unique_lock
.
See example code below:
#include <map>
#include <string>
#include <mutex>
#include <memory>
class MapWithMutex
{
public:
int readFromMap(const std::string& key)
{
std::unique_lock<std::mutex>(mtx);
//add some check if elements exists
return myMap[key];
}
void insertToMap(const std::string& key, int value)
{
//add check if element doesn't already exist
std::unique_lock<std::mutex>(mtx);
myMap[key] = value;
}
private:
std::map<std::string,int> myMap;
std::mutex mtx;
};
int main() {
MapWithMutex thSafeMap;
//pass thSafeMap object to threads
return 0;
}
Remember to make critical section as small as possible