Search code examples
c++multithreadingstlvector

Atomically std::vector::push_back() and return index


I need to create a function which appends a value to a vector and returns the index of the value that was just appended.

Example:

int append(std::vector<int>& numbers, int number){
  int retval = numbers.size();
  // what if some other thread calls push_back(number) in between these calls?
  numbers.push_back(number);
  return retval;
}

I would like to do this atomically so that the returned index is always correct even when there may be multiple threads appending values to the vector. It would have been easy if push_back returned the index of the item just added. How can I guarantee that the correct index is returned?


Solution

  • std::vector has no built in thread support. You could use boost::mutex to extend it:

    int append(std::vector<int>& numbers, int number){
      boost::mutex::scoped_lock slock( my_lock );
      int retval = numbers.size();
      numbers.push_back(number);
      return retval;
    }
    

    You need to protect any read/write operation in such way. Another way is to create wrapper class for std::vector that will extend it with thread support. Check this question for details.