0804-----Linux Base----------Timer TIMERFD

Source: Internet
Author: User
Tags readable thread class

1.Basic usage of TIMERFD

The timers in the 1.1 TIMERFD series are not signals, but are FD-readable, and commonly used functions are timerfd_create, Timerfd_settime, and Timerfd_gettime, The function and use of these functions is also relatively simple, here is a brief example (1.2) to illustrate its usage, the Create parameter clock_realtime is a relative time, when the system time is changed, will be adjusted, there is a parameter clock_monotonic, It is absolute time, changing the system time has no effect on it, here the flags is generally set to 0, the front said that the timer expires as TIMERFD readable, so you can add the FD to the IO Multiplexing Model (1.3).

1.2 Create a timer, Set the parameters of the time interval structure, turn on the timer, so that a timer can work, but here to note that the TIMERFD timer expires when the FD has data readable, so once the time, must be the data to go out, or the timer will not work properly.

 #include <stdio.h> #include <stdlib.h> #include <        string.h> #include <sys/timerfd.h> #define ERR_EXIT (m) do {perror (M);    Exit (Exit_failure); }while (0)/* * Timer TIMERFD Basic usage */int main (int argc, const char *argv[]) {//create timer for FD int timerfd = timerfd_create (CLOC    K_realtime, 0);    if (TIMERFD = =-1) err_exit ("Timerfd_create"); Turn on the timer and set the timer to the time of the struct itimerspec new_value;    Const memset (&new_value, 0, sizeof new_value); New_value.it_value.tv_sec = 5; Initial expiry time new_value.it_interval.tv_sec = 1;    The interval after if (timerfd_settime (TIMERFD, 0, &new_value, NULL) = =-1) err_exit ("Timerfd_settime");    Char buf[1024] = {0};    int ret; while (ret = read (TIMERFD, buf, sizeof buf)) > 0) {printf ("ret =%d, read data:%s\n", ret, BUF);//} Clos    E (TIMERFD); return 0;} 

1.3 timer and poll are used together, The TIMERFD is added to the poll listener array, and poll will hear the TIMERFD when the timer expires. Here poll adopts the horizontal trigger mode, that is, for a certain FD readable, if not do read processing, then the next time will return to the FD, that is, the FD has been readable, waiting to be read out, if not read out, has been triggered, then the timer is useless.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <poll.h> #include <sys/        Timerfd.h> #define ERR_EXIT (m) do {perror (M);    Exit (Exit_failure); }while (0)/* * Timer TIMERFD and Epoll use */int main (int argc, const char *argv[]) {//create timer for FD int TIMERFD = Timerfd_cre    Ate (clock_realtime, 0);    if (TIMERFD = =-1) err_exit ("Timerfd_create"); Turn on the timer and set the timer to the time of the struct itimerspec new_value;    Const memset (&new_value, 0, sizeof new_value); New_value.it_value.tv_sec = 5; Initial expiry time new_value.it_interval.tv_sec = 1;    The interval after if (timerfd_settime (TIMERFD, 0, &new_value, NULL) = =-1) err_exit ("Timerfd_settime");    Char buf[1024] = {0};    struct POLLFD event[1];    EVENT[0].FD = TIMERFD;    Event[0].events = Pollin;        while (1) {int ret = poll (event, 1, 10000);//The longest time to wait is 10s if (ret = = 1) err_exit ("poll");        else if (ret = = 0) printf ("timeout\n"); else{           if (read (TIMERFD, buf, sizeof buf) = =-1)//here if not read will always be triggered err_exit ("read");        printf ("foobar....\n"); }    }}

" Span style= "font-family: Song body; font-size:18pt; " >1.4 a timer class , where the functions of the TIMERFD class are encapsulated into classes, the user provides the action to be performed when the timer expires (that is, the use of a function callback), the benefit of which is the object-oriented benefits of providing an interface function to the outside world, which is more secure by invoking the object directly when needed.

#ifndef __timer_h__#define __timer_h__#include "NonCopyable.h" #include <functional> #include <sys/timerfd.h >class timer:noncopyable{public:typedef std::function<void () > TimerCallback;//Timer callback function type Ti        Mer ();        ~timer (); void SetTimer (int init_val, int inter_val);        The parameters are the initial expiration time and the interval of the subsequent each time void Setcallback (const TimerCallback &callback);    void Runtimer ();        Private:int Timerfd_;        struct Itimerspec howlong_; TimerCallback Callback_; User-defined logic}; #endif/*__timer_h__*/#include "Timer.h" #include <string.h> #include <stdlib.h> #include <        stdio.h> #include <poll.h> #include <iostream> #define ERR_EXIT (m) do {perror (M);    Exit (Exit_failure);    }while (0) Timer::timer () {timerfd_ = timerfd_create (clock_realtime, 0);    if (Timerfd_ = =-1) err_exit ("Timer_create"); memset (&howlong_, 0, sizeof howlong_);} Timer::~timer () {close (timerfd_);} void Timer::SetTimer (int init_val, int inter_val) {//Parameter howlong_.it_value.tv_sec = Init_val; Howlong_.it_interval.tv_sec = Inter_val;} void Timer::setcallback (const TimerCallback &callback) {callback_ = callback;} void Timer::runtimer () {//Turn on Timer if (timerfd_settime (timerfd_, 0, &howlong_, NULL) = =-1) err_exit ("Timerfd    _settime ");    struct POLLFD event[1];    EVENT[0].FD = Timerfd_;    Event[0].events = Pollin;    Char buf[1024];    int ret;       while (1) {ret = poll (event, 1, 1000);//polling every 1s if (ret = 1) err_exit ("poll");       else if (ret = = 0) std::cout << "Timerout" << Std::endl;            else{if (read (Timerfd_, buf, sizeof buf) = =-1) err_exit ("read"); Callback_ (); Call user Logic}}} #include "Timer.h" #include <iostream>using namespace std;void func () {cout << "Hello World "<< Endl;}    int main (int argc, const char *argv[]) {Timer TM;    Tm.settimer (3, 1); Tm.setcAllback (func);    Tm.runtimer (); return 0;}

Combination of 2.Timer and Thread classes

2.1 Program Writing Ideas:

A) Bind the user logic to the Timer;

b) Bind the timer's Runtimer method to Thread;

c) that is, the operation of the timer is encapsulated in the thread, the execution thread is the timer.

2.2 Source Program Manifest

a) Thread.h Thread.cpp

#ifndef __thread_h__#define __thread_h__#include "NonCopyable.h" #include <pthread.h> #include <functional        >class thread:noncopyable{public:typedef std::function<void () > Threadcallback;        Thread ();        Explicit Thread (const threadcallback &callback);        ~thread ();        void Setcallback (const threadcallback &callback);        void Start ();    void join ();        private:static void *thread_func (void *);        pthread_t tid_;        Threadcallback Callback_; bool Isstarted_;}; #endif/*__thread_h__*/#include "Thread.h" Thread::thread (): Tid_ ( -1), Isstarted_ (false) {}thread::thread (const thre Adcallback &callback): Tid_ ( -1), Isstarted_ (false), Callback_ (callback) {}thread::~thread () {if (isstarted _) Pthread_detach (tid_);} void Thread::setcallback (const threadcallback &callback) {callback_ = callback;}    void Thread::start () {isstarted_ = true; Pthread_create (&tid_, NULL, Thread_func, this);}    void Thread::join () {isstarted_ = false; Pthread_join (Tid_, NULL);}    void *thread::thread_func (void *arg) {Thread *pt = Static_cast<thread *> (ARG);    Pt->callback_ (); return NULL;}

b ) Test_timer.cpp

#include "Timer.h" #include "Thread.h" #include <iostream>using namespace std;/* * Use the combination of classes Thread and Timer class */class Tim erthread{public    :        timerthread ();        void print (); function        void Starttimerthread () executed when the timer expires;    Private:        Thread thread_;        Timer Timer_;}; Timerthread::timerthread () {}void timerthread::p rint () {    cout << "Hello World" << Endl;} void Timerthread::starttimerthread () {    Timer_.settimer (3, 1);    Timer_.setcallback (Bind (&timerthread::p rint, this));    The thread class is used to encapsulate the operation of the Timer    Thread_.setcallback (Bind (&timer::runtimer, &timer_));    Thread_.start ();    Thread_.join ();} int main (int argc, const char *argv[]) {    TimerThread tt;    Tt.starttimerthread ();    return 0;}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.