Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the iterator invalidation rules mean thread safety?

Here in this Stack Overflow answer it is listed the iterator invalidation rules for the standard containers in C++11. Particularly, there are for insertion:

  1. [multi]{set,map}: all iterators and references unaffected [23.2.4/9]
  2. unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B where z is the maximum load factor and B the current number of buckets. [23.2.5/14]

    erasure:

  3. [multi]{set,map} and unordered_[multi]{set,map}: only iterators and references to the erased elements are invalidated

Do these rules mean I can safely do insertion and erasure in one thread, and safely in another thread access, look for (using find) elements as long as these elements are not the ones being inserted and erased in the first thread, and make sure that rehashing is not happening?

If not, what do these rules exactly mean?

like image 855
Allanqunzi Avatar asked Dec 11 '22 21:12

Allanqunzi


1 Answers

The fact that iterators to elements of the container are not invalidated in no way implies thread safety on the container itself. For example, the size member variable would need to be modified atomically which is a totally separate issue from iterators being invalidated (or not) on insertion/deletion.

tl;dr; No.

These rules simply tell you when an iterator to an element is invalidated by an operation. For example, when a vector resizes, the underlying array is reallocated elsewhere so if you had an iterator (or pointer) to an element, it would no longer be valid after the resize (because it would be pointing to deleted elements of the old array).

like image 87
Borgleader Avatar answered Dec 13 '22 11:12

Borgleader