c++ Multithreading with std library: slower than expected -


i tried play std library ,in particular thread one. idea fill matrix , without multithreading. have 8 cores.

void fillmatrix(int id, std::vector<std::vector<double>> & lmatrix,int inthread){      (int = 0; < 10000; ++i){         if (i % inthread == id){             (int j = 0; j < 10000; ++j){                 lmatrix[i][j] = 123456.0;             }         }     }  }   void testmt(int inthread){      std::vector<std::thread> lpool;     std::vector<std::vector<double>> lmatrix(10000, std::vector<double>(10000));      (int = 0; < inthread; ++i){         lpool.push_back(std::thread(std::bind(&fillmatrix,i, lmatrix,inthread)));     }      (std::thread & t : lpool){         t.join();     } } 

the main code :

int main(){     const clock_t begin_time1 = clock();     testmt(1);     std::cout << float(clock() - begin_time1) / clocks_per_sec; } 

testmt(1) takes 2.1 seconds run, while testmt(8) takes 7.032 seconds.

any idea ? thanks.

your code not run want to. after threads run, you'll notice none of elements of lmatrix set 123456.0. because std::bind copies vector that's sent thread. need use std::ref(lmatrix) in bind call work , use same matrix.

change

std::bind(&fillmatrix,i, lmatrix,inthread) 

to

std::bind(&fillmatrix, i, std::ref(lmatrix), inthread) 

a significant portion of increased execution time therefore caused copy overhead; being 10000 x 10000 allocations , copies being made per thread launch (and deallocations afterwards).