3

Here is what I'm trying to do, I want a part of code in main() to run on a continuous loop to check the input and other things. And another part of code to run on delay of every X milliseconds.

while(true) //want this to run continuously, without any delay. { Input(); } while(true) //want this to run every 1500 miliseconds. { DoSomething(); Sleep(1500); //from <windows.h> library. } 

Is there any way to do this properly?

4
  • 1
    why not use a timer? Commented Dec 29, 2019 at 20:10
  • 2
    Does this answer your question? Simple example of threading in C++ Commented Dec 29, 2019 at 20:10
  • 1
    Use timer instead of Sleep. You cannot have 2 while. Commented Dec 29, 2019 at 20:12
  • What's the target system? Many OSes have the ability to do this without threads, for example Overlapped IO in Windows. or epoll or select with a timeout on Linux. Commented Dec 29, 2019 at 20:18

2 Answers 2

6

You'll want to run two threads:

void f() { while(true) //want this to run continuously, without any delay. { Input(); } } void g() { while(true) //want this to run every 1500 miliseconds. { DoSomething(); Sleep(1500); //from <windows.h> library. } } int main() { std::thread t1(f); std::thread t2(g); ... 
Sign up to request clarification or add additional context in comments.

Comments

0

I used high_resolution_clock to keep track of time. I used simple while loop for continuous update and added if condition to do some specific task, after a time interval.

#include<chrono> //For clock using namespace std::chrono; high_resolution_clock::time_point t1, t2; int main() { t1 = high_resolution_clock::now(); t2 = {}; while(true) { CheckInput(); //Runs every time frame t2 = high_resolution_clock::now(); if(duration_cast<duration<float>>(t2 - t1).count()>=waitingTime) { DoSomething(); //Runs every defautWaitTime. t1 = high_resolution_clock::now(); t2 = {}; } } return 0; } 

Comments