Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 / C++03 and std::vector thread safety

I am reading about thread safety of various stl containers from this link Now I came across this point which states for C++11 only

Different elements in the same container can be modified concurrently by different threads, except for the elements of std::vector<bool> (for example, a vector of std::future objects can be receiving values from multiple threads)

Does this mean if I have a method such as this which is being used by multiple threads simultaneously (notice the method does not have any locks)

void ChangeValue(int index , int value)
{
   someVector[index] = value;
}

Is the above method safe. My understanding is that it is safe for C++11 only. However when I look at the other statement mentioned in the link

All const member functions can be called concurrently by different threads on the same container. In addition, the member functions begin(), end(), rbegin(), rend(), front(), back(), data(), find(), lower_bound(), upper_bound(), equal_range(), at(), and, except in associative containers, operator[], behave as const for the purposes of thread safety (that is, they can also be called concurrently by different threads on the same container). More generally, the C++ standard library functions do not modify objects unless those objects are accessible, directly or indirectly, via the function's non-const arguments, including the this pointer.

I come to the conclusion that in C++03 the above method can be safely used as well. Kindly let me know if my understanding is correct.

like image 644
MistyD Avatar asked Jun 30 '15 22:06

MistyD


1 Answers

It is meaningless to ask whether something is thread-safe under the C++03 standard - C++03 and earlier didn't have any concept of threads or thread safety.

ChangeValue is data race-free (as defined by C++11 and later) as long as no two threads pass the same argument for index, or else calls passing the same argument are synchronized with each other by some means external to the function.

like image 131
Igor Tandetnik Avatar answered Oct 24 '22 10:10

Igor Tandetnik