简体   繁体   中英

C++11: How can I join a std::thread as soon as its execution function exits?

I have the following class that has a std::thread as one of its member fields:

class MyClass {
private:
    std::thread auxThread;
    void run();
public:
    ~MyClass();
    void start();
}

MyClass:~MyClass() {
    if (auxThread.joinable())
        auxThread.join();
}

void MyClass::run() {
    //do stuff
}

void MyClass::start() {
    auxThread = std::thread (&MyClass::run, this); //Move assignment
}

I can start the auxThread on-demand thanks to initializing it with an empty constructor and later move-assigning it to a std::thread object associated with an actual thread of execution (via the start() function), but to minimize system resource usage I'd like to join() auxThread with the main thread immediately after run() has exited ie when auxThread's work is done instead of in the MyClass destructor. It looks like condition_variable could be used to wake a sleeping main thread and accomplish this, but I don't want to block the main thread except (hopefully) briefly with join().

Two questions:

  1. Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread, or is the thread and all associated resources released when the execution function exits (such that join() would presumably be unnecessary and return immediately)?

  2. Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?

Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread

Maybe. It depends on your implementation, but typically not.

is the thread and all associated resources released when the execution function exits

Probably, and if not, then as soon as possible by the OS. This is also implementation defined.

Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?

Yes, but it wouldn't make any sense. The only thing that join does is block until the function being executed is done. Calling join again after run finished executing is unnecessary and basically a no-op.

Also, the "resources" from the thread are minimal. I wouldn't expect that a lot of memory would be allocated just for a single thread like yours. RAM is pretty cheap nowadays, so you shouldn't worry about that, as you are not executing 5M threads in parallel, which would make no sense on a conventional computer anyways.

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