c++std-call-once

Execute a function only once insider a loop that is called at each 0.1 seconds c++


I have an Update function in my application, it is called each second.. I want to do a statement check and if it's true to execute that function only once in that Update function. If statement is false to reset std::call_once

void Update()
{
    if (cond)
        std::call_once(flag1, [&capture](){ MyFunction(capture.arg); });
    else
        //Some codes to reset call once 
}

HOW i can reset call once?


Solution

  • std::call_once is guaranteed to occur only once even from multiple threads and you can't reset it as it will defeat its very purpose. However you can try this snippet which call your function every 0.1 sec.

    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
        }
    
    }
    

    Edited: Since the update is already triggered every 0.1sec, you can use the std::call_once here, or you can simply use a static flag like so:

     void Update()
     {
        static bool first_time = true;
        if(first_time) {
           first_time = false;
           MyFunction(capture.arg);
        }
    }