Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .join is still necessary when all other thread have finished before the main thread?

Learning C++ multi-threading.
In my example, thread helper1 and helper2 have finished executing before the main thread finished. However, program crashes. I specifically, took out .join() statements, to see how program would behave, expecting no errors, since main() calls std::terminate after two other threads have finished.

void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(5));
    std::cout << "t1\n";
}

void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "t2\n";
}

int main()
{

    std::cout << "starting first helper...\n";
    std::thread helper1(foo);

    std::cout << "starting second helper...\n";
    std::thread helper2(bar);


    std::this_thread::sleep_for(std::chrono::seconds(10));

    std::cout << "waiting for helpers to finish..." << std::endl;
    //helper1.join();
    //helper2.join();

    std::cout << "done!\n";
}
like image 785
newprint Avatar asked Apr 07 '14 06:04

newprint


People also ask

What happens if you try to .join a thread that has ended?

It checks isAlive, so it will just return. Some people have a misconception that join somehow causes threads to be joined together and mixed or something. In fact, all it does is wait for the other thread to terminate if it hasn't already.

What does thread .join do?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

Is thread join necessary?

No join or System. exit necessary. Each thread lives its own life. As long as at least one thread is running, the program keeps running.

What happens if you don't join threads?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything. But this some point is non-deterministic.


1 Answers

I'd say that your question doesn't make sense, because it's based on a false assumption. The only way to know that a thread has finished is when the thread's join() returns. Before join() returns, it is not the case that "the thread has finished". It may be true that some statement within the thread's execution has completed (e.g. the printing of a message, or better, the writing of an atomic variable), but the completion of the thread function itself is not measurable in any way other than by joining.

So none of the threads "have finished" until you join them.

like image 130
Kerrek SB Avatar answered Sep 18 '22 09:09

Kerrek SB