-1

I had to create timelapse function to wait for X amount of time in a loop.

The following code checks the boolean value of m_abortTimeLapseThread but after running for an hour I noticed the execution time of this code created 10 seconds delay. Is there a way to check m_abortTimeLapseThread as frequently as possible and wait for X amount of time in the function without the kind of delay I observed ?

void Acquisition::TimeLapseCount() {

int max10msWaitTimes = m_timeLapseInMs / 10;
while (true) {

    m_timeLapseImageSaved = true;

    for (int i = 0; i < max10msWaitTimes; i++)
    {
        if (m_abortTimeLapseThread) {
            return;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }


}
}

Thanks,

user1296153
  • 575
  • 6
  • 23
  • why do you use a loop instead of just waiting for the full amount? Of course your loop and checking the boolean adds overhead, a tiny one, but its adds every 10ms, so in total I can believe that after an hour it adds up to seconds – 463035818_is_not_an_ai Feb 19 '18 at 19:16
  • 1
    [Stopping long-sleep threads](//stackoverflow.com/a/29775639) – 001 Feb 19 '18 at 19:23
  • 1
    @user463035818 I need a loop to check m_abortTimeLapseThread because another thread may decide to exit the program then I want this function to be completed. That's why I have to use a loop. – user1296153 Feb 19 '18 at 19:25
  • 2
    If it's not 100% necessary use bool as abort flag, you can use [conditional varible](http://www.cplusplus.com/reference/condition_variable/condition_variable) and [wait for timeout](http://www.cplusplus.com/reference/condition_variable/condition_variable/wait_for/) – Pavlo K Feb 19 '18 at 19:26
  • Is `m_abortTimeLapseThread` an std::atomic? – super Feb 19 '18 at 20:14
  • @super Yes and m_timeLapseImageSaved is also an std::atomic. – user1296153 Feb 19 '18 at 20:25
  • What is the code supposed to do? Does it perform a regular action and need to be halted on demand? – Galik Feb 19 '18 at 20:36

1 Answers1

1

You could measure total time elapsed.

void Acquisition::TimeLapseCount() {
    auto waitUntil = std::chrono::system_clock::now() + std::chrono::milliseconds(m_timeLapseInMs);
    while (true) {

        m_timeLapseImageSaved = true;

        while (waitUntil > std::chrono::system_clock::now())
        {
            if (m_abortTimeLapseThread) {
                return;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }

        waitUntil += std::chrono::milliseconds(m_timeLapseInMs);
    }
}
super
  • 12,335
  • 2
  • 19
  • 29