简体   繁体   中英

C++ std::thread should be created on heap or on stack

Lets say i have a thread that is being created and detached on the stack like this:

void foo()
{
    while(true){};
}

void runThread()
{
    std::thread t(foo);
    t.detach();
}

int main()
{
    runThread();
}

The program means nothing of course, But what happens after we detach and exit runThred ? it was allocated on the stack so basically t will be destroyed after we exit runThred , but the thread itself will go on running regardless to the main thread because it is detached.

Is the best practice in such an example is to create it on the heap and save a pointer to it doing whatever (dcor) after that?

Or it means nothing if the t variable is destructed and we should just "ignore" it?

The std::thread object represents a handle to the thread through which it can be operated on. But once you call detach there is no connection between the object and the actual thread of execution.

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