Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to create a new thread inside a while loop but it makes the program crash.
Any ideas on how to fix this?

C++
#include <thread>
using namespace std;

void function1()
{
    
}

int main()
{
    while(true)
    {
        thread thread(function1);
    }
    return 0;
}


What I have tried:

I have tried to create a thread outside the while loop and it works fine but i need it to
start inside the while loop.
Posted
Updated 22-Feb-20 22:44pm
v2
Comments
Dave Kreskowiak 22-Feb-20 23:58pm    
The code you posted would endlessly create threads until the system ran out of resources, fairly quickly.

Why on earth would you endlessly create threads, that did nothing as the code you posted suggests.

1 solution

The problem is that the thread goes out of scope without having been joined, so the program crashes. See here[^]

Assuming that this did work, you would get a crash anyway, since you have an infinite loop. Eventually you would run out of resources to create more threads. Maybe this is just a short demo to show what you are up against?
 
Share this answer
 
v2
Comments
Lockesty 23-Feb-20 0:54am    
YES thats the answer i was looking for, thank you so much !
I thought it detached the thread automatically when i dont join it, atleast that was my logical conclusion.

I actually already thought it might be because of the infinite repeat so i tested it inside the while loop but under conditions but it still crashed

Thankfully detaching the thread does the trick

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900