dimanche 6 janvier 2019

Concurrently iterating through a map while inserting, in what way is it unsafe

Note: I know this is unsafe and undefined by the standard, looking to see if it's defined by my compiler, or if it's safe in practice.

I'm iterating over a map range in one thread, while potentially inserting in another thread

// thread 1:
for(auto it = map.begin(); it != map.end(); ++it){
    // it's okay if "it" is out of order, repeats an element, or skips an element
    // it's bad  if "it" can skip map.end() or turn to mush (invalid ptr)
}

// thread 2:
map[Key(...)] = Type(...); // insertions are extremely rare

This is unsafe, but um... how unsafe? This map serves as an optimization hint to ease thread contention, so it itself can't contribute to that contention. If the possible outcomes are only that the inserted element might be missed, or that it'll read elements out of order or twice, this is acceptable and won't break anything.

Would doing this turn iterators to soup or causes map.end() to be missed? These are the only two outcomes that could ruin my life.

Aucun commentaire:

Enregistrer un commentaire