Destruction order when jthread is a class member

103 Views Asked by At

I have a class which handles synchronization of some threads.

class ThreadHandler {
    std::vector<std::jthread> threads;
    std::mutex mut;
    std::condition_variable cv;
    int some_int;
    // some other synchronization related variables
};

In C++, member destructors are called in reverse order, so the destructor for cv is called before the destructor for threads. Because the destructor for threads joins the jthreads, there's a period of of time when cv and mut have been destructed and the jthreads are still running. Is that a problem?

1

There are 1 best solutions below

0
user253751 On

Thanks to comments:

Could the threads use cv and mut after they're destroyed? – user253751
@user253751 in the code, yes. The threads run until std::stop_token::stop_requested returns true, which doesn't happen until join is called, I think. – Bobby

the asker knows the code could use these objects after they're destroyed.

So the question is: Is it okay to use an object after it's been destroyed?

And the answer is: No.

The computer doesn't care about which order you write your member variables, but it does care about using objects after they're destroyed. If the threads had no chance to use cv and mut after they were destroyed, then it would be okay. If they could use cv and mut after they're destroyed, then it's not okay and you have to fix that or your program will sometimes crash.