Thread-sharing a std::map

Hi everyone,

I have a std::unordered_map<int, CustomClass*> map that I share between two threads. When either thread loops through this map, it does so like this:

1
2
3
4
5
6
std::unordered_map<int, CustomClass*> _map(map); // Make thread safe copy
std::unordered_map<int, CustomClass*>::iterator it;
// Iterate through all elements:
for (it = _map.begin(); it != _map.end(); it++) {
  //..
}


Rarely, my application freezes. I've done some performance reports with visual studio and it seems to point to this line:
std::unordered_map<int, CustomClass*>

Am I doing this wrong? Do I need to use a mutex here after all?
stl container are not thread safe.

Line 1 may very well crash if map is modified within another thread. So yes, you need mutexes
Do I need to use a mutex here after all?


As a general rule of thumb... you need to use a mutex (or memory barriered atomic variables) for all accesses shared between two or more threads. There are very few exceptions to this.

Lock free algorithms are certainly possible, but they're a lot more complicated than you might expect, and I would not attempt them until you've thoroughly studied and understand the complications involved.

This guy's blog entry on the subject is particularly enlightening:

http://cbloomrants.blogspot.ca/2009/01/01-25-09-low-level-threading-junk-part.html
Thanks for the responses! I'll keep this in mind when working with multiple threads. I guess it makes sense that line one isn't safe after all. I'll make sure to read the blog too.

Cheers!
Topic archived. No new replies allowed.