Program crashes when trying to initiate a thread in while loop

I want to create a new thread inside a while loop but it makes the program instantly crash on start. Any ideas on how to fix this?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <thread>
using namespace std;

void function1()
{

}

int main()
{
    while(true)
    {
        thread thread(function1);
    }
    return 0;
}
It better crash on start, how many threads do you think that's going to make? Put conditions, don't let it loop infinitely.

Technically, that code won't crash "instantly", but the while loop will run many times before a single second has even passed and it'll crash from all the threads it's made.
Create a reasonable number of threads, and join them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <thread>
#include <vector>
using namespace std;

void function1()
{
    cerr << "func\n";
}

int main()
{
    vector<thread> th;
    for (int i = 0; i < 4; ++i)
        th.emplace_back(function1);
    for (auto& t: th)
        t.join();
}

Last edited on
Sorry i forgot to mention i already thought it mightve been because of the infinite loop so i tested it under conditions but it still crashed.

Thankfully i found the solution, it seems that the thread goes out of scope and terminates the
program. I detached it with the thread.detach(); command and it did the job
Topic archived. No new replies allowed.