Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass reference of multidimensional map to a function with std::threads

i wrote the code in following way

#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;
}

i passed 2D map m reference to hi function and i updated but it not reflecting in main function. When i print m.size() it printing zero only.how can i pass the 2D map reference to function using thread?

like image 490
Pavan Avatar asked Oct 15 '25 04:10

Pavan


1 Answers

The thread constructor will copy its arguments, so one solution is to use std::ref:

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

This creates a wrapper object that behaves as a reference. The wrapper itself will be copied (semantically, in reality the copy may be elided), but the underlying map will not. So overall, it will act as if you had passed by reference.

like image 196
juanchopanza Avatar answered Oct 16 '25 17:10

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!