Can I access a C++11 std::map entry while inserting/erasing from another thread?

前端 未结 4 1174
半阙折子戏
半阙折子戏 2021-01-12 15:16

Can I access (without locking) an std::map entry while another thread inserts/erases entrys?

example pseudo C++:

typedef struct {
   int value;
   in         


        
4条回答
  •  忘掉有多难
    2021-01-12 16:03

    No. And yes.

    Two or more threads can perform const operations on a map, where a few non-const operations also count (operations that return non-const iterators, hence are not const, like begin and similar stuff).

    You can also modify the non-key component of an element of a map or set while other operations that do not read/write/destroy said element's non-key component run (which is most of them, except stuff like erase or =).

    You cannot erase or insert or other similar non-const map operations while doing anything with const and similar map operations (like find or at). Note that [] can be similar to erase if the element is added.

    The standard has an explicit list of non-const operations that count as const for the purposes of thread safety -- but they are basically lookups that return iterator or &.

提交回复
热议问题