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

I need to create a function that adds a value to a vector and returns the index of the value just added.

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 right, even if multiple threads can be added to the vector. It would be easy if it push_backreturned the index of the element just added. How can I guarantee the return of the correct index?

+5
source share
5 answers

std::vectordoes not have native thread support. You can use boost::mutexto expand 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;
}

/ . - - std::vector, . , .

+11

STL ( push_back()), - STL.

+3

Visual Studio 2010 concurrent_vector , . .

, Intel TBB + , , -.

+2

, .

0

( , ).

, - , :

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);
  int newSize = numbers.size();
  //this bit is as a short-cut in common, easy, cases
  if(newSize = retval + 1) //no need for further complication
    return retval;
  while(++retval < newSize)
    if(numbers[retval] == number)
      return retval;
  //If we get this far, numbers have been deleted, not added. More discussion below.
}

, 3, 3, 3, 3, , 3. , .

, - , , , , ( , newSize, [retval] ). , ( , , ) , .

, - , , .

0

All Articles