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

有些话、适合烂在心里 提交于 2019-12-01 05:50:23

No no no no no!

map::erase modifies the links between the map entries and that messes with the search algorithm used in map::at. You can use the elements during an erase, but you can not execute the searching algorithm itself!

I've created an illustration program. On my machine this program sometimes print OK, sometimes throws a map exception - that means that the search is gone wrong. Increasing the number of reading threads make the exception appear more often.

#include <iostream>
#include <thread>
#include <map>
#include <cassert>

std::map<int, int> m;

// this thread uses map::at to access elements
void foo()
{
  for (int i = 0; i < 1000000; ++i) {
    int lindex = 10000 + i % 1000;
    int l = m.at(lindex);
    assert(l == lindex);
    int hindex = 90000 + i % 1000;
    int h = m.at(hindex);
    assert(h == hindex);
  }
  std::cout << "OK" << std::endl;
}

// this thread uses map::erase to delete elements
void bar()
{
  for (int i = 20000; i < 80000; ++i) {
    m.erase(i);
  }
}

int main()
{
  for (int i = 0; i < 100000; ++i) {
    m[i] = i;
  }

  std::thread read1(foo);
  std::thread read2(foo);
  std::thread erase(bar);

  read1.join();
  read2.join();
  erase.join();

  return 0;
}

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 &.

No. std::map are not thread safe. Intel's thread building block (tbb) library has some concurrent containers. Check tbb

As long as the threads are not accessing the same address at the same time there will be no problem.

But for a direct answer to your question, no, it is not thread safe so you can't do it without locking without any errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!