If I reference an object in the secondary thread B* b
and one data members of this object is modying through the principal thread (write) , should I protect only the data or the whole object b
?
I precise I'm just refering the whole object not reading the shared data (here _x), suppose that after referring it I'll send it to another class and inside it I'll read _x. I need to protect my data where I'm reading it ?
If getB()
return a validate object. then the b
removed from the principal thread (where b
was created) I find my self with a dangling pointer B* b
in the secondry thread ?
class B{
public:
B(){}
void setX(int x){
// here I lock to protect _x
_x = x;
}
int getX(){
// here I lock to protect _x
return _x;
}
private:
int _x = 0;
};
class A{
public:
A(B* b)
: _b(b)
{}
B* getB(){
return _b;
}
private:
B* _b;
};
class thread{
public:
thread(A* a)
: _a(a)
{}
void threadMain(){
// this is the secondry thread
B* b = _a->getB(); // // it is fine to not protect inside getB() ?
// pass b to another class .. C* c = new c(b...) .. c will
// read _x via b and I'll use mutex there (getX())
}
std::thread member1Thread() {
return std::thread([=] { threadMain(); });
}
private:
A* _a;
};
int main(){
// this is the principal thread
B* b = new B();
A a(b);
thread th(&a);
std::thread thread(th.member1Thread());
a.getB()->setX(100);
// what if this thread delete b after _a->getB() gave a significant object --> B* b will be dangling pointer ?
return 0;
}