kip622
kip622

Reputation: 399

Do I need a mutex on a vector of pointers?

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.

Upvotes: 0

Views: 243

Answers (1)

Igor
Igor

Reputation: 1855

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

Upvotes: 1

Related Questions