简体   繁体   中英

How to end a thread safely

In C++ I can create a thread as follows

#include <thread>

using namespace std;

void f()
{
    // Do something
    cout<<"Finished! I am going to return!"<<endl;
}

int main()
{
    thread my_thread(&f);

    // Do other things that, say, take a LOOOONG time to be executed, much longer than the execution time of the thread
}

The thread my_thread starts, runs my function f. The main thread keeps executing the main() function, and while it is still executing the other thread reaches the end of f() and returns. What happens then? I am ok like this? The thread is just closed and I don't have to call anything else? Or does the thread stay there hanging forever and I need to call some cleanup function?

Please note that I don't need to do any synchronization and no value needs to be returned from f().

What happens then?

You attempt to destroy a joinable thread object, which causes the program to terminate.

I am ok like this?

You shouldn't do that. Either call my_thread.join() to wait for the thread and clean up its resources, or my_thread.detach() to make it clean up automatically when the thread exits.

You must call my_thread.join() once you're finished using the thread. Calling join() tells the operating system that your finished using the thread and the program can safely terminate, effectively "joining" your thread with the main thread.

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