carak
carak

Reputation: 97

Run function and keep loop running c++

How to run a function within loop and still keep loop running without waiting when the function2 completes?

int main(){
 function1();
}

function1(){
   while(1){
      function2();   }
}

function2(){
   //some task that needs to do independently while, While loop runs
}

Upvotes: 0

Views: 1052

Answers (2)

GavinHenderson5
GavinHenderson5

Reputation: 51

Spawn a new thread with function2 and then start them in function 1 in the loop where you previously called it. It should compile but it will spawn infinite threads and something will go wrong so be careful. Sounds like threading is your solution though

Upvotes: 0

Hatted Rooster
Hatted Rooster

Reputation: 36483

You can launch function2 async:

#include <future>
void function1(){
   while(1){
      std::async(std::launch::async, function2);   
   }
}

Do note that this will generate a lot of instances that all call function2(), you should probably throttle that.

Upvotes: 4

Related Questions