我有一个使用很多std::map
结构的程序。现在,我想将它们与多个线程一起使用,并假定插入或删除键可能会更改整个数据结构并并行破坏它。但是当我不添加新密钥时,应该没事吧?
以下程序显示了我想做什么:
#include <omp.h>
#include <iostream>
#include <map>
int main(int const argc,char const *const *const argv) {
// Take a map and allocate the elements,but not fill them at this point.
std::map<int,int> map;
int size = 10000;
for (int i = 0; i < size; ++i) {
map[i];
}
// Go through the elements in parallel and write to them,but not create any
// new elements. Therefore there should not be any allocations and it should
// be thread-safe.
#pragma omp parallel
{
int const me = omp_get_thread_num();
#pragma omp for
for (int i = 0; i < size; ++i) {
map[i] = me;
}
}
// Now all threads access all the elements of the map,but as the map is not
// changed any more,nothing bad should happen.
#pragma omp parallel
{
int const me = omp_get_thread_num();
int self = 0;
for (int i = 0; i < size; ++i) {
if (map[i] == me) {
++self;
}
}
#pragma omp critical(cout)
std::cout << "Thread " << me << " found " << self << " entries.\n";
}
}
然后用以下代码进行编译:
$ g++ -fopenmp -O3 -Wall -Wpedantic -g -fsanitize=address -o concurrent-map concurrent-map.cpp
这似乎可以在四个线程上正常工作。如果我注释掉第一个for循环并让线程填充地图,则它会由于我的期望而导致分段错误。
当然,我无法以这种方式证明std::map
是线程安全的,但至少不能证明是负面的。我可以并行使用std::map
吗?