Search code examples
c++c++17signalsatomicrace-condition

Ending a loop on time expiration


I have a long computation in a loop, which I need to end prematurely if allowed compute time expires (and return a partially computed result). I plan to do it via SIGALARM handler and a timer:

// Alarm handler will set it to true.
bool expired = false;

int compute ()
{
    int result;

    // Computation loop:
    for (...) {
        // Computation here.

        if (expired)
            break;
    }
    return result;
}

My question is: how to correctly define the expired variable (volatile bool or std::atomic<bool>, or std::sig_atomic_t, etc), how to set it true in the signal handler (just an assignment or atomic operation), and how to check its value in the compute function?

This is a single-threaded C++17 code...


Solution

  • If you aren't using multiple threads, you don't need an atomic operation. Just set the global variable expired = true in the signal handler.

    EDIT: as @Frank demonstrated below, the compiler might optimize it out. You can avoid this by declaring expired as volatile bool expired = false;