简体   繁体   English

运行函数并保持循环运行C ++

[英]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? 如何在循环内运行一个函数,并在function2完成时不等待就保持循环运行?

int main(){
 function1();
}

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

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

You can launch function2 async: 您可以启动function2异步:

#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. 请注意,这会生成很多实例,所有实例都调用function2() ,您可能应该限制它。

Spawn a new thread with function2 and then start them in function 1 in the loop where you previously called it. 用function2产生一个新线程,然后在先前调用它的循环的function 1中启动它们。 It should compile but it will spawn infinite threads and something will go wrong so be careful. 它应该编译,但是会产生无限线程,并且会出问题,所以要小心。 Sounds like threading is your solution though 听起来像线程是您的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM