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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With