Data races in STL containers
While reading in Effective STL from Scott Meyers I came across item 12 (Have realistic expectations about thread safety of STL containers). Scott basically says that multiple readers and multiple writers to different containers are safe. One should not expect more.
Then I remember Bjarne Stroustrup talking about thread safety that came with C++11. I don't recall which video it was, IMHO a keynote of a conference. So what exactly does the standard say for C++11, containers and thread safety?
23.2.2 Container data races [container.requirements.dataraces]
1 For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, > back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].
2 Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the > same sequence, excepting vector
, are modified concurrently.
So there is more in the box than before. Lucky me, since I've started learning C++ not so long ago :-)
Bonus chatter: C++ is the first computer language where I ever looked up what the standard says. Maybe it's this kind of mystery that attracts me to C++.
But for now let's have a look at Scott's first example from item12:
vector<int> v;
...
vector<int>::iterator first5(find(v.begin(), v.end(), 5)); // Line1
if (first5 != v.end()){ // Line2
*first5 = 0; // Line3
}
Another thread could change the content of vector v, after line1 has been completed. Do the extended data race rules do us any good here? I think not. Albeit saying that begin and end shall be const, I don't see why this would prevent a second thread changing the data in v, after line 1 was computed. Thus the iterator first5 could be invalid right after line1. v.end() should be const but for how long? I am quite sure that it can change between line 1 and 2.
That does not mean, that the committee did a bad job or that there is no such thing as thread safety in C++11 STL containers. Everything is in order here, but you still need to think about what you are doing, "C++11 is thread safe now" is no excuse!