C ++ STL map / vector of vectors and thread safety

I was wondering if the following code would be considered thread safe. I think it should be, but I'm not too familiar with what is happening under the hood.

Basically, I have this function in the Foo class, which will be called in the main thread and accepts the vector as anrgument, i.e.

void Foo::func( vector<int> v)

In Foo, I also have a private member,

vector< vector<int> > vecOfVec;

Inside, funcI will just drop any new ones von vecOfVecand check the size v. If it is vsmaller than its expected size, I would like to start another thread that fills with vsome known predefined values, for example:

void Foo::func( vector<int> v)
{
    int size = v.size();
    int index = vecOfVec.size();

    vecOfVec.push_back(v);

    if (size < 1000)
    {
        boost::thread t( boost::bind( &Foo::PushBackZeros, this, vecOfVec, index) );
    }
}

Foo::PushBackZeros , 'vecOfVec [index]' , 1000;

vecOfVec. , , vecOfVec.

- , ? STL? , . !

+3
3

, . , , - ? , , , , () . , , , , .

+8

Foo::PushBackZeros , Foo::func( vector<int> v), , . , .

0

vecOfVec , boost:: bind , boost:: ref .

, , , .

, , "this".

To answer the original question, although for what you want:

  • If vecOfVecs can be modified, then any of its members may be invalid so that it is not thread safe.
  • Clicking elements in one of the internal vectors will not invalidate any other member vectors, so you can have different streams filling in different elements of the vector at the same time, as long as they are all there.
  • If you reserve ahead, you can push_back more members to your vector until this capacity is reached, and this will invalidate the existing members.
0
source

Source: https://habr.com/ru/post/1786158/


All Articles