在每 0.1 秒调用一次的循环中仅执行一次函数 c++
Execute a function only once insider a loop that is called at each 0.1 seconds c++
我的应用程序中有一个 Update
函数,它每秒被调用一次。我想做一个语句检查,如果在那个 Update 函数中只执行一次该函数是真的。如果语句为 false 则重置 std::call_once
void Update()
{
if (cond)
std::call_once(flag1, [&capture](){ MyFunction(capture.arg); });
else
//Some codes to reset call once
}
我怎样才能重置通话一次?
std::call_once 即使在多个线程中也保证只发生一次,您不能重置它,因为它会破坏它的真正目的。但是,您可以尝试每 0.1 秒调用一次函数的代码片段。
void Update()
{
static std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now() - std::chrono::milliseconds(100);
if (std::chrono::high_resolution_clock::now() - start_time >= std::chrono::milliseconds(100)) {
start_time = std::chrono::high_resolution_clock::now();
MyFunction(capture.arg); // ensure that your func call takes less than 0.1 sec else launch from a separate thread
}
}
已编辑:
由于更新已经每 0.1 秒触发一次,您可以在此处使用 std::call_once,或者您可以简单地使用静态标志,如下所示:
void Update()
{
static bool first_time = true;
if(first_time) {
first_time = false;
MyFunction(capture.arg);
}
}
我的应用程序中有一个 Update
函数,它每秒被调用一次。我想做一个语句检查,如果在那个 Update 函数中只执行一次该函数是真的。如果语句为 false 则重置 std::call_once
void Update()
{
if (cond)
std::call_once(flag1, [&capture](){ MyFunction(capture.arg); });
else
//Some codes to reset call once
}
我怎样才能重置通话一次?
std::call_once 即使在多个线程中也保证只发生一次,您不能重置它,因为它会破坏它的真正目的。但是,您可以尝试每 0.1 秒调用一次函数的代码片段。
void Update()
{
static std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now() - std::chrono::milliseconds(100);
if (std::chrono::high_resolution_clock::now() - start_time >= std::chrono::milliseconds(100)) {
start_time = std::chrono::high_resolution_clock::now();
MyFunction(capture.arg); // ensure that your func call takes less than 0.1 sec else launch from a separate thread
}
}
已编辑: 由于更新已经每 0.1 秒触发一次,您可以在此处使用 std::call_once,或者您可以简单地使用静态标志,如下所示:
void Update()
{
static bool first_time = true;
if(first_time) {
first_time = false;
MyFunction(capture.arg);
}
}