[英]Execute a function only once insider a loop that is called at each 0.1 seconds c++
我的應用程序中有一個Update
函數,每秒調用一次。我想執行一條語句檢查,如果在該Update函數中僅執行一次該函數是否成立。 如果語句為假,則重置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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.