1
#include <iostream>
#include <thread>

void func() {
    std::cout << "Hello";
}

int main() {
    std::vector<std::thread> threads; 
    int n = 100;
    for (int i = 0; i < n; i++) {
         std::cout << "executing thread" << std::endl;
         threads.push_back(std::thread(func));
    }
}

My program prints "executing thread" once and it ends. What is the cause?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
rjlion795
  • 515
  • 1
  • 5
  • 16

4 Answers4

1

After this loop completes the destructor of std::vector<std::thread> is invoked. std::thread destructor calls std::terminate if the thread was neither detached nor joined, like in your case.

To fix that, add the following after the loop:

for(auto& thread : threads)
    thread.join();
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
1

Make sure you join the threads to wait for them all to complete:

for (auto &thread : threads) {
    thread.join();
}

If the program continues after this point and doesn't exit immediately, flush the output since it may be buffered:

std::cout << std::flush;
jspcal
  • 50,847
  • 7
  • 72
  • 76
0

Even if you don't join, it should still print "executing thread" 100 times.

Perhaps the problem is using "endl" instead of "std::endl"

Abdul Ahad
  • 826
  • 8
  • 16
0

Once the loop creating the threads is done, your program continues. And it continues to leave the main function which causes all variables defined inside the main function to go out of scope and their life-time ending. This leads to the destruction of the objects, including the vector which then leads to all the thread object in the vector being destructed.

And as noted by others, the destruction of a thread object will lead to program termination if the thread is not joined or detached.


While the other answers tell you to join the threads (which IMO is the recommended solution here) there is another possible solution: To detach the threads.

While this will lead to the std::terminate function to be called and prematurely terminate your program, this will lead to another problem, as leaving the main function ends the process and all its threads.

If you for some reason what your threads to continue to live on after the main function exits, you need to detach the threads and exit the "main thread" using an operating-system specific function. This will leave the process running with all your created threads still chugging along.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • i guess you didn't get my question. the loop executes only once i.e "executing thread" is only printed once. This is the problem I am getting. – rjlion795 Jun 07 '18 at 11:13