Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to explicitly join threads?

So this seems pretty straightforward:

#include <iostream>
#include <thread>

void second() {
    cout << "Don't thread on me!" << endl;
}

int main() {
    thread t { second };
    t.join();

    return 0;
    cin.get();
}

If I don't include join() then the system calls abort(). I don't understand this, shouldn't the thread exit on its own? Having to join threads seems like it will make the code harder to encapsulate properly. What's the deal with this?

like image 802
sircodesalot Avatar asked Aug 29 '13 19:08

sircodesalot


2 Answers

That is part of the design of the C++ threading library. You don't need to join the thread, you can also detach it. But I would not recommend that you default to detach-ing threads, as that brings it's own set of complications.

Contrary to what you are saying, I don't think this makes the code harder to encapsulate at all. There are different levels of abstraction, and choosing the thread level means that you need to be aware that there are threads and you need to handle them.

For different things you may choose different levels of abstractions, for example:

int main() {
   auto f = std::async([](){ std::cout << "Don't tread on me\n" << std::flush; });
   f.get();      // Wait for the task to complete
}
like image 160
David Rodríguez - dribeas Avatar answered Sep 28 '22 07:09

David Rodríguez - dribeas


By default threads have to join so that the spawning thread can keep track of and wait for its children to complete (for example you delegate a bunch of work to 2+ threads and then join them all to signal when the work is done).

You can use detach to cause the thread to detach from its spawning thread and that will cause the threads to run independently.

like image 36
Mark B Avatar answered Sep 28 '22 07:09

Mark B