std::map thread-safety

前端 未结 2 1696
轮回少年
轮回少年 2020-12-05 00:40

Is reference to object in std::map is thread safe?

std::map< std::string, Object >   _objects;

map can be changed from many threads a

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 00:50

    Elements in a map are stable, they do not get moved or invalidated unless the element is erased from the map. If only one thread is writing to a given object, and changes to the map itself are correctly synchronized, then I believe it will be safe. I'm sure it's safe in practice, and I think it's safe in theory too.

    The standard guarantees that distinct elements can be modified by different threads, in [container.requirements.dataraces]

    Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector, are modified concurrently.

    This only allows you to modify the elements, not to insert new elements into the map while modifying elements. For some containers, such as std::vector, modifying the vector itself might also modify elements by reallocating and moving them, but [associative.reqmts]/9 ensures std::map won't invalidate existing elements.

    Since no member function of std::map is required to access the second member of its elements (i.e. the mapped_type) I think [res.on.data.races]/5 says no other thread will conflict with writes to that member when modifying the map. (Thanks to Yakk for that final piece of the puzzle)

提交回复
热议问题