Read-only thread safety
What is mean term "Read-only thread s开发者_StackOverflow社区afety" Can anyone post some code example?
The example could be some STL container, initialized like this
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
If not modified, this vec
can be used by several threads accessing its fields. It's safe, while the members of vec
are not changed nor the memory it occupies.
int n = vec.at(0);// good. many threads can do this
// many threads could do this too
for( std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it )
{
cout << *it << endl;
}
It's not safe though if other thread does some writing/modification over vec
while someone is reading it.
vec.push_back(3); // bad: vec could get expanded and the data relocated
vec[ 0 ] = 5; // bad: someone could read invalid data
精彩评论