简体   繁体   中英

std::thread in C++11, how to ensure a thread is finished inside a destructor

I want to make sure a thread is completed before an object is destructed.

Here is the most basic example I could think of:

struct User {
    std::thread worker_thread;

    ~User() {
        if (worker_thread.joinable()) {
            worker_thread.join();
        }
    }
};

Is this a correct approach to the problem?

It is not correct, as join() may throw an exception, and you don't want to let any exception escape any destructor. From Herb Sutters Exceptional C++ in the section Destructors That Throw and Why They're Evil. :

Observe the canonical exception safety rules: Never allow an exception to escape from a destructor or from an overloaded operator delete() or operator delete[](); write every destructor and deallocation function as though it had an exception specification of " throw() ."

I also think it is fine as mentioned in the comment, but you need to make sure to properly quit a thread if needed.

For instance, if you have a loop counter counting down slowly, you would need to properly close before the long waiting queue. Even more to that when you have an "endless" boolean condition for instance that has to be toggled, et cetera.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM