read/write in std::map

Hi,

I have one thread that would very frequently insert into std::map (but never erase) and another thread that iterates and reads from the map. Would that cause problem? If so what would be the best remedy besides using mutex? (I need low latency and could not afford a lot of inter-locking)

Writer code:
1
2
3
4
5
6
7
auto it = my_map.find(key);
if (it != my_map.end()) {
	return it->second;
} else {
	order_viewer_list.insert(make_pair(key, obj));
	return obj;
}


Reader code:
1
2
3
4
for (auto& it : my_map) {
	long key = it.first;
	// do something with it.second
}
I have one thread that would very frequently insert into std::map (but never erase) and another thread that iterates and reads from the map. Would that cause problem?

Yes. If one thread is depending on the internal state of the object to be consistent and one thread is changing the internal state of the object, you have problems.

If so what would be the best remedy besides using mutex?

Couldn't tell you. Perhaps someone else will chime in or perhaps google might be your friend.

http://stackoverflow.com/questions/19143228/creating-a-standard-map-that-is-thread-safe
No standard container is thread safe. You cannot do this without mutex.

The mutex has a member try_lock(...) to avoid the wating:

http://www.cplusplus.com/reference/mutex/mutex/try_lock/
Topic archived. No new replies allowed.