Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 986
Agnel Kurian Avatar asked Aug 10 '10 09:08

Agnel Kurian


2 Answers

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.

like image 128
Kirill V. Lyadvinsky Avatar answered Sep 19 '22 23:09

Kirill V. Lyadvinsky


STL containers are not thread-safe (even the call to push_back() alone), you'll have to solve this problem on your own - use some suitable synchronization primitives outside STL.

like image 37
sharptooth Avatar answered Sep 20 '22 23:09

sharptooth