开发者

Read-only thread safety

开发者 https://www.devze.com 2023-01-22 07:23 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号