Do I need a mutex on a vector of pointers?

廉价感情. 提交于 2019-12-02 16:08:25

问题


Here is a simplified version of my situation:

void AppendToVector(std::vector<int>* my_vector) {
  for (int i = 0; i < 100; i++) {
    my_vector->push_back(i);
  }
}

void CreateVectors(const int num_threads) {
  std::vector<std::vector<int>* > my_vector_of_pointers(10);
  ThreadPool pool(num_threads);
  for (for int i = 0; i < 10; i++) {
    my_vector_of_pointers[i] = new std::vector<int>();
    pool.AddTask(AppendToVector,
                 &my_vector_of_pointers[i]);
  }
}

My question is whether I need to put a mutex lock in AppendToVector when running this with multiple threads? My intuition tells me I do not have to because there is no possibility of two threads accessing the same data, but I am not fully confident.


回答1:


Every thread is appending different std::vector (inside AppendToVector function) so there is no need for locking in your case. In case you change your code in the way more than one thread access same vector then you will need lock. Don't be confused because std::vectors you are passing to AppendToVector are them-selfs elements of main std::list, it matters only that here threads are manipulating with completely different (not shared) memory



来源:https://stackoverflow.com/questions/26937825/do-i-need-a-mutex-on-a-vector-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!