简体   繁体   中英

Amateur can't understand std::thread usage

I hereby pardon for such a general title.
I am writing a physical simulation application which displays data in 3D using OpenGL, and one of the functions which is responsible for some heavy calculations is appearing to hold the performance down a bit. I would like them to be done "on the background" without freezing the application for a few seconds. However, std::thread doesn't seem to work in my case.
The function I am trying to thread has a lot of computations in it, it allocates some memory here and there, calls other functions and uses classes, if that matters. I've created a wrapper function, from which I try to start a thread:

void WrapperFunction(void)
{  
std::thread t(DoSomethingSerious);  
t.join();  
}

However, it appears that it has zero effect, just like if I called DoSomethingSerious directly. What could be the problem?

join() waits for the thread to finish, before proceeding. That's what joining a thread means.

You have two options.

1) Instantiating a std::thread , and proceed to do whatever else needs to be done, and only join the thread once everything is done.

2) detach() the thread. The detached thread will continue to execute independently, and cannot be joined any more. In this case, you will have to make other arrangements for waiting until the thread stops.

That is because you directly call t.join() . The std::thread::join function waits for the thread to finish before returning. As you yourself notice, the effect is that there is no difference from just calling the function.

More useful would be to do something else between the thread creration and where you wait for the thread. Something like the following pseudo-code:

void WrapperFunction(void)
{
    // Create thread
    std::thread t(DoSomethingSerious);

    // Lots
    // of
    // code
    // doing
    // other
    // things

    // Wait for thread to finish
    t.join();
}

However, it appears that it has zero effect.

Sure, your code in the main thread is just suspended until everything in the asynchronous thread is finished.

If you have intermediate actions between starting the thread and doing the join() , you should notice the effect :

void WrapperFunction(void) {  
    std::thread t(DoSomethingSerious);  
    // Do something else in parallel
    t.join();  
}

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