Should you always put join() after launching a thread?

I wonder if there is any advantage putting join() not immediately after launching a thread?

std::thread t(func);

// some code ...

t.join();

does it give you any advantage or it’s always preferable to use it after a thread launch?

std::thread t(func);
t.join();

// some code ...

>Solution :

If you use join() right after starting the new thread then it will block (wait) execution on the join() call until the new thread is finished running (defeating the whole purpose of the parallelization you get from starting the new thread). Therefore, if you want to execute "some code" on the main thread while thread t is executing, join() should come after "some code".

Leave a Reply