0

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 } 
6
  • 4
    You need multiple threads. en.cppreference.com/w/cpp/thread/thread Commented Jun 29, 2017 at 14:12
  • man7.org/linux/man-pages/man3/popen.3.html Commented Jun 29, 2017 at 14:13
  • So you want to run function1() and function2() at the same time? Commented Jun 29, 2017 at 14:13
  • Do you realize that if you don't wait for function2(), you're going to get a lot of instances of it running simultaneously. Commented Jun 29, 2017 at 14:13
  • Are you trying to create o fork bomb? :-D Commented Jun 29, 2017 at 14:28

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But, will this block the main thread forever since you didn't assign the result of std::async to the std::future instance?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.