How to implement a timer with interruption in C++?

后端 未结 2 1005
攒了一身酷
攒了一身酷 2021-01-07 01:00

I\'m using the GCC compiler and C++ and I want to make a timer that triggers an interruption when the countdown is 0.

Any Ideas? Thanks in advance.

相关标签:
2条回答
  • 2021-01-07 01:38

    An easy, portable way to implement an interrupt timer is using Boost.ASIO. Specifically, the boost::asio::deadline_timer class allows you to specify a time duration and an interrupt handler which will be executed asynchronously when the timer runs out.

    See here for a quick tutorial and demonstration.

    0 讨论(0)
  • 2021-01-07 01:53

    One way to do it is to use the alarm(2) system call to send a SIGALRM to your process when the timer runs out:

    void sigalrm_handler(int sig)
    {
        // This gets called when the timer runs out.  Try not to do too much here;
        // the recommended practice is to set a flag (of type sig_atomic_t), and have
        // code elsewhere check that flag (e.g. in the main loop of your program)
    }
    
    ...
    
    signal(SIGALRM, &sigalrm_handler);  // set a signal handler
    alarm(10);  // set an alarm for 10 seconds from now
    

    Take careful note of the cautions in the man page of alarm:

    alarm() and setitimer() share the same timer; calls to one will interfere with use of the other.

    sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.

    Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time.

    0 讨论(0)
提交回复
热议问题