如何使用std :: threads将多维映射的引用传递给函数

时间:2013-07-23 18:35:26

标签: c++ multithreading c++11 reference

我按照以下方式编写代码

#include <iostream>
#include <thread>
#include <map>
using namespace std;
void hi (map<string,map<string,int> > &m ) {
   m["abc"]["xyz"] =1;
   cout<<"in hi";
}
int main() {
   map<string, map<string, int> > m;
   thread t = thread (hi, m);
   t.join();
   cout << m.size();
   return 0;
}

我将2D地图m参考传递给hi函数并且我更新但它没有反映在main函数中。当我打印m.size()时它只打印零。我可以使用线程将2D地图引用传递给函数吗?

1 个答案:

答案 0 :(得分:8)

线程构造函数将复制其参数,因此一种解决方案是使用std::ref

thread t = thread (hi, std::ref(m));

这将创建一个作为引用的包装器对象。包装器本身将被复制(在语义上,实际上可以省略副本),但底层地图不会。总的来说,它会像你通过参考一样传递。