Question

I have a problem with code below, after threads finish working, the output of the array is a rabish data, while it's working correctly without threads, any one can help me and explain why !!!!!

#include<iostream>
#include <thread> 

using namespace std;


class Case1{

public:
 int *pplAges[5];
 Case1(){
 *pplAges= new int[5];
 }

 void addToAges(int Age, int index){
 pplAges[index] = new int;
 *pplAges[index] = Age;
 cout<< *pplAges[index] <<endl;

 }


};

void f1(Case1 passedObj,int age,int index)
{

passedObj.addToAges(age,index);

}

void main(){

 Case1 C;

thread t1(f1,C,13,0);
t1.join();

thread t2(f1,C,14,2);
t2.join();

cout<<*C.pplAges[0]<<endl;
cout<<*C.pplAges[2]<<endl;
}
Was it helpful?

Solution

Threads copy their arguments, so your threads never change the C. If you want a reference explicitly, you have to wrap it with std::ref (or std::cref for constant references):

void f1(Case1& passedObj, int age, int index)
{

    passedObj.addToAges(age, index);

}

void main(){

    Case1 C;

    thread t1(f1, std::ref(C), 13, 0);
    t1.join();

    thread t2(f1, std::ref(C), 14, 2);
    t2.join();



    cout << *C.pplAges[0] << endl;
    cout << *C.pplAges[2] << endl;
}

OTHER TIPS

try to change

void f1(Case1 passedObj,int age,int index)

to

void f1(Case1* passedObj,int age,int index)

and pass the thread &C

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top