调用函数时出现问题.C++

Having problem with calling function. C++

本文关键字:问题 C++ 函数 调用      更新时间:2023-10-16

我写了一个 SetInterval 和 SetTimeOut 函数作为 JavaScript 函数,但我不能设置低 100 毫秒,也不能调用两个 SetInterval。请帮帮我!

包括

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
using namespace std::chrono;
using namespace std;
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
);

使用参数函数设置超时

template <typename Proc, typename T>
void SetTimeOut(T & val, Proc p, unsigned long long n) {
unsigned long long def = ms.count(); // starting point
unsigned long long ds = ms.count() + n; // the time what need become equal to def

while (def != ds) {
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
); // time updates
def = ms.count(); // converting to nums

}
p(val); // calling the main function
}

相同,但调用非参数函数

template <typename Proc>
void SetTimeOut(Proc p, unsigned long long n) {
unsigned long long def = ms.count() ;
unsigned long long ds = ms.count() + n;
while (def != ds) {
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
); // time updates
def = ms.count();
}
p(); // Main function calling
}

p - 我们要调用的函数,n - 应该经过多少时间,s - 应该重复多少次。 使用非参数函数设置间隔

template <typename Proc>
void SetInterval(Proc p, unsigned long long n, long long s) {
//here there are call in turn of function SetTimeOut
for (int i = 1; i != s + 1; i++) SetTimeOut(p, n * i);
}
//Same, but for parameter function
template <typename T, typename Proc>
void SetInterval(T val, Proc p, unsigned long long n, long long s) { 
for(int i = 1; i != s+1; i++) SetTimeOut(val, p, n * i);
}
//Example with struct
struct Car{
string model;
double speed;
int fuel;
};

主要功能

int main() {
Car Car;
int i = 1;
Car.fuel = 200;
Car.speed = 10.2;

//Example with lambda function.
SetInterval(Car,[&](struct Car){
Car.speed += 1.9;
Car.fuel -= 1.2;
cout << Car.speed << " " << Car.fuel << endl;
}, 900, 10); // it will end after 10 calls with 0.9 sec interval
//Second Example, which is not working
SetInterval(i, [&](int i){ i++; cout << i << endl;}, 500, 5);
}

我认为这是因为通话时间交叉,但我不知道如何解决它。

不要这样做:

while (def != ds) {
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
); // time updates
def = ms.count(); // converting to nums
}
p(val); // calling the main function

这是一个自旋循环。 它只会固定整个CPU内核,同时不断检查"是时候了吗"。 至少,在那里放一个睡眠声明并检查<=而不是!=以防你的时钟跳跃。

while (def <= ds) {
duration<milliseconds> tosleepfor(ds-def);
this_thread::sleep_for(tosleepfor);
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
); // time updates
def = ms.count(); // converting to nums
}
p(val); // calling the main function

但这是你的设计的根本问题。 Javascript有一个内置的消息泵,用于执行异步工作 - 包括设置带有回调的计时器。 C++没有这样的设施。 您的SetTimeout函数实际上并未设置超时。 它只是使程序停止,直到到达时间。

您必须使用操作系统的 GUI 线程或拥有自己的消息泵送概念,以按特定间隔调度回调。