Reputation:
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?
Upvotes: 3
Views: 433
Reputation:
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;
}
Upvotes: 0
Reputation: 27577
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);
...
Upvotes: 6