C++ Call by Reference in multithread causes problem

Viewed 47

I am gonna ask my question from some simplified example. Let's assume that we have the following code blocks.

bool myfunction(const std::vector<int>& Map){
    for(int i=0; i<Map.size();i++){
        std::cout<<Map[i]<<std::endl;
}

int main(){
    std::vector<int> Map={1,1,1,1,0,1,0,0,1,1,1,1};
    std::thread th1(myfunction, std::ref(Map));
    Map={0,0,1,0,0,0,1,1,1,1,0,1};
    std::thread th2(myfunction, std::ref(Map));
    th1.join();
    th2.join();
}

It outs the second map twice. So I was just asking, if there is any way to protect the first Map vector variable without touching main() function.

0 Answers
Related