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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With