jeudi 3 novembre 2016

Does joining a member thread accessing other members of its parent class in the parent's destructor result in undefined behavior?

One of my coworkers claims that as soon as an object's destructor invocation begins, all accesses to the object's members done by a thread (that's a member of the object itself) are UB.

This implies that calling std::thread::join during the destructor of an object is UB if the thread is accessing any of the object's other members.

I briefly looked in the latest standard draft, under "Object Lifetime", but couldn't find something that gave me a conclusive answer.

Does the following code (on wandbox) introduce undefined behavior? What's the part of the standard that clarifies this interaction?

struct A 
{
    atomic<bool> x{true};
    thread t;

// Capturing 'this' is part of the issue.
// The idea is that accessing 'this->x' becomes invalid as soon as '~A()' is entered.
//           vvvv
    A() : t([this]
            { 
                while(x) 
                {
                    this_thread::sleep_for(chrono::milliseconds(100)); 
                }
            }) 
    { 
    }

    ~A() 
    { 
        x = false; 
        t.join(); 
    }
};

int main()
{
    A a;
}

Aucun commentaire:

Enregistrer un commentaire