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


learning c++ multi-threading.
in example, thread helper1 , helper2 have finished executing before main thread finished. however, program crashes. specifically, took out .join() statements, see how program behave, expecting no errors, since main() calls std::terminate after 2 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 helpers finish..." << std::endl;     //helper1.join();     //helper2.join();      std::cout << "done!\n"; } 

i'd question doesn't make sense, because it's based on false assumption. way know that thread has finished when thread's join() returns. before join() returns, not case "the thread has finished". may true statement within thread's execution has completed (e.g. printing of message, or better, writing of atomic variable), completion of thread function not measurable in way other joining.

so none of threads "have finished" until join them.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -