C++ main process waiting for the child thread problem and its solution

0X00 C++11 <thread> library

Today I need to use multi-threading when doing experiments, so I searched for some knowledge that is too C++ multi-threaded programming.
I learned that in C++11, a new library was added to support multithreading:

#include <thread>

The method of creating a new thread is as follows:

std::thread t(function)

Which function()is defined function, function()the function name

When the thread is created, there are two ways to start, one is .join(), the other is.detach()

0X10. The pitfall of detach() function

He said the two methods above, .join()is the thread starts, and blocks, that is, if the child thread does not end, then, the main thread or the main process will not continue;
and .detach()that is to open up a separate thread, the main thread will Separation, doing your own, will not affect the main thread.

This sounds good, but here is the pit.
If you created it like this, don’t think you can sit back and relax

void function()
{
    
    
//...
}
int main()
{
    
    
//...
std::thread t(function)
t.detach();

return 0;
}

At this time the question is coming, do you think the main program will wait for you?

But not, you will find that your thread hasn't been running long (assuming it is a thread with a long running time), the main program exits.

In other words, the main program does not actually have to wait. The reason is that the compiler will be returnoptimized for exitthat is forced to withdraw from the process, of course, not a process, thread naturally gone.

0X20 solution-pthread_exit(NULL)

So how can we make the main thread wait?

Very simple, use the following function:

pthread_exit(NULL); 

It means to wait for all threads to end before ending the main process

void function()
{
    
    
//...
}
int main()
{
    
    
//...
std::thread t(function)
t.detach();

pthread_exit(NULL); 
return 0;
}

The problem is solved simply

Although it is very simple, once a mistake is made, it is sometimes difficult to detect. So if you want the main thread to wait for the child threads (which is usually the case), then please add - pthread_exit(NULL)right!

Alright, let’s say this today, see you next time~

Guess you like

Origin blog.csdn.net/rjszz1314/article/details/104724395