从另一个线程插入/擦除时,我可以访问C++ 11 std :: map条目吗?

gj1*_*j13 5 c++ multithreading stdmap c++11

我可以访问(不锁定)std :: map条目而另一个线程插入/删除entrys吗?

示例伪C++:

typedef struct {
   int value;
   int stuff;
}some_type_t;

std::map<char,some_type_t*> my_map;   

//thread 1 does:
my_map.at('a')->value = 1;

//thread 2 does:
some_type_t* stuff = my_map.at('b');

//thread 3 does:
my_map.erase('c');

//I'm not modifying any elements T is a pointer to an previously allocated "some_type_t" 
Run Code Online (Sandbox Code Playgroud)

std C++ 11说所有成员都应该是线程安全的(erase()不是const).

Yak*_*ont 12

没有.是的.

两个或多个线程可以const在地图上执行操作,其中一些非const操作也计数(返回非const迭代器的操作,因此不是const,类似begin和类似的东西).

您还可以修改的元素的非关键部件mapset同时不读取/写入等操作/删除上述元素的非关键部件的运行(这是大多数人,除了喜欢的东西erase=).

在使用和类似的地图操作(例如或)做任何事情时,你不能erase或者insert或者其他类似的非const地图操作.请注意,可以类似于添加元素.constfindat[]erase

该标准有一个明确的非const操作列表,这些列表是const为了线程安全的目的 - 但它们基本上是返回iterator或查找的查找&.


Csq*_*Csq 9

不不不不不!

map::erase使用中使用的搜索算法修改地图条目和混乱之间的链接map::at.您可以在擦除期间使用元素,但不能执行搜索算法本身!

我已经创建了一个插图程序.在我的机器上,这个程序有时会打印OK,有时会抛出一个地图异常 - 这意味着搜索出错了.增加读取线程的数量会使异常更频繁地出现.

#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;
}
Run Code Online (Sandbox Code Playgroud)