Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe if detached std::thread uses object that went out of scope?

Imagine that I start a std::thread which runs a member function of an object. What happens if that object goes out of scope in main function where I created the thread?

class ThreadClass {
    public:
    ThreadClass(int i) : _a(i) {
    }

    void foo() {
        sleep(10);
        std::cout << "Is it safe here? " << _a << std::endl;
    }
    int _a;
};

int main() {
    {
        ThreadClass obj(3);
        std::thread t(&ThreadClass::foo, &obj);
        t.detach();
    }

    // Here obj goes out of scope
    // What about thread?

    sleep(20);
    return 0;
}

Would be this an undefined behavior?

like image 950
Mert Mertce Avatar asked Jan 07 '23 07:01

Mert Mertce


2 Answers

No, that code isn’t safe. The thread holds a non-owning reference to the object (via a copy of the pointer &obj). Once the object goes out of scope, that’s a dangling reference.

like image 156
Konrad Rudolph Avatar answered Jan 29 '23 02:01

Konrad Rudolph


Yes it is undefined behavior. More specifically, you will end up with a segmentation fault because the thread is trying to access some object which no longer exists. So here is what I'd suggest:

  • Declare the obj somewhere that will not go out of scope during the lifetime of any thread(Probably global).
  • Pass by value instead of a reference.
  • Create an object using new and pass the pointer to the thread using std::shared_ptr. (In this case you will have to make sure the thread calls the delete operation, to avoid a memory leak).
like image 23
Pooja Nilangekar Avatar answered Jan 29 '23 03:01

Pooja Nilangekar