Swoole source code Learning Record (15th) -- Timer module Analysis

Source: Internet
Author: User

Swoole source code Learning Record (15th) -- Timer module Analysis

 

1. Timer1.1.swTimer _ interval_node

Statement:

// swoole.h 1045-1050htypedef struct _swTimer_interval_node{    struct _swTimerList_node *next, *prev;    struct timeval lasttime;    uint32_t interval;} swTimer_interval_node;
Member Description
Next, prev Chain table successor, precursor pointer
Struct timeval lasttime Duration
Uint32_t interval Interval

Note:
The swTimer_interval_node struct is a linked list node that stores a fixed interval timer. lasttime indicates the time that the current timer has elapsed since the last execution, and interval stores the timer interval.
This struct is used for swoole's original timer-related operations.

1.2.swTimer _ node

Statement:

// swoole.h 1052-1058htypedef struct _swTimer_node{    struct _swTimer_node *next, *prev;    void *data;    uint32_t exec_msec;    uint32_t interval;} swTimer_node;
Member Description
Next, prev Chain table successor, precursor pointer
Void * data Data domain, storing additional variables
Uint32_t exec_msec Time when the timer should be executed
Uint32_t interval Interval (useless, should be discarded)

Note:
The swTimer_node struct is a linked list node that stores a timer that needs to be executed at a specified time. exec_msec is the specified time for the current timer to be executed, and interval stores the timer interval.
This struct is used for swoole's after function operations.

1.3.swTimer

Statement:

// swoole.h 1060-1081htypedef struct _swTimer{    swTimer_node *root;    /*--------------timerfd & signal timer--------------*/    swHashMap *list;    int num;    int interval;    int use_pipe;    int lasttime;    int fd;    swPipe pipe;    /*-----------------for EventTimer-------------------*/    struct timeval basetime;    /*--------------------------------------------------*/    int (*add)(struct _swTimer *timer, int _msec, int _interval, void *data);    int (*del)(struct _swTimer *timer, int _interval_ms);    int (*select)(struct _swTimer *timer);    void (*free)(struct _swTimer *timer);    /*-----------------event callback-------------------*/    void (*onTimer)(struct _swTimer *timer, int interval_msec);    void (*onTimeout)(struct _swTimer *timer, void *data);} swTimer;
Member Description
SwTimer_node * root After linked list root node
SwHashMap * list Timer linked list root node
Int num Current number of timers
Int interval Timer basic response Interval
Int use_pipe Whether to use pipe Communication
Int lasttime Duration (obsolete)
Int fd MPs queue write fd
SwPipe pipe MPs queue
Struct timeval basetime Basic EventTimer time

Note:
The entity object of the swTimer struct timer. It is used to store, manage, and execute many scheduled tasks, including two different types of scheduled tasks: timer and after.

1.4.swTimer common operation function 1.4.1.swTimer _ init

Statement:

// swoole.h 1083int swTimer_init(int interval_ms, int no_pipe);

Function: initialize a swTimer object.
Core source code:

    // timer.c 38-94h    swTimer *timer = &SwooleG.timer;    timer->interval = interval;    timer->lasttime = interval;#ifndef HAVE_TIMERFD    SwooleG.use_timerfd = 0;#endif    timer->list = swHashMap_new(SW_HASHMAP_INIT_BUCKET_N, free);    if (!timer->list)    {        return SW_ERR;    }    if (SwooleG.use_timerfd)    {        if (swTimer_timerfd_set(timer, interval) < 0)        {            return SW_ERR;        }        timer->use_pipe = 0;    }    else    {        if (use_pipe)        {            if (swPipeNotify_auto(&timer->pipe, 0, 0) < 0)            {                return SW_ERR;            }            timer->fd = timer->pipe.getFd(&timer->pipe, 0);            timer->use_pipe = 1;        }        else        {            timer->fd = 1;            timer->use_pipe = 0;        }        if (swTimer_signal_set(timer, interval) < 0)        {            return SW_ERR;        }        swSignal_add(SIGALRM, swTimer_signal_handler);    }    if (timer->fd > 1)    {        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, SW_FD_TIMER, swTimer_event_handler);        SwooleG.main_reactor->add(SwooleG.main_reactor, SwooleG.timer.fd, SW_FD_TIMER);    }    timer->add = swTimer_add;    timer->del = swTimer_del;    timer->select = swTimer_select;    timer->free = swTimer_free;

Source code explanation:
Obtain the timer object in SwooleG and set the timer response interval and lasttime parameters. If HAVE_TIMERFD is not defined, timerfd is not used. Then, use HashMap to initialize the timer linked list.
If timerfd is used, call the swTimer_timerfd_set function to set the basic response interval of the timer and set whether to use pipelines.
If signalfd is used instead of timerfd, determine whether an MTS queue is required first. If so, create an MTS queue and obtain the MPs queue write fd. Then, call the swTimer_signal_set function to set the precise timer provided by the Linux system, and use swSignal_add to add the callback function swTimer_signal_handler for processing the SIGALRM signal.
Add the MPs queue write fd to the listener of main_reactor and set the callback function swTimer_event_handler.
Finally, set the four callback operation functions of swTimer.

1.4.2.swTimer _ signal_handler

Statement:

// swoole.h 1085void swTimer_signal_handler(int sig);

Function: callback handler for SIGALRM Signals
Core source code:

    // timer.c 338-344h    SwooleG.signal_alarm = 1;    uint64_t flag = 1;    if (SwooleG.timer.use_pipe)    {        SwooleG.timer.pipe.write(&SwooleG.timer.pipe, &flag, sizeof(flag));    }

Source code explanation:
Set signal_alarm of SwooleG to true. If an MTS queue is set to true, a flag notification Timer is sent through the MTS queue.

1.4.3.swTimer _ event_handler

Statement:

// swoole.h 1086int swTimer_event_handler(swReactor *reactor, swEvent *event);

Function: the timer event processing callback function.
Core source code:

    // timer.c 323-334h    uint64_t exp;    swTimer *timer = &SwooleG.timer;    if (read(timer->fd, &exp, sizeof(uint64_t)) < 0)    {        return SW_ERR;    }    SwooleG.signal_alarm = 0;    return swTimer_select(timer);

Source code explanation:
Try to read data from the MPs queue. If the data is read successfully, reset the signal_alarm tag of SwooleG and call swTimer_select to process the scheduled task;

1.4.4. Other functions

SwTimer_node_insert, swTimer_node_print, swTimer_node_delete, and swTimer_node_destory are linked list operation functions, which are not analyzed in detail.

1.5.Timer private operation function 1.5.1.swTimer _ signal_set

Statement:

// timer.c 24hstatic int swTimer_signal_set(swTimer *timer, int interval);

Function: Call the settimer function to start the timer.
Core source code:

    struct itimerval timer_set;    int sec = interval / 1000;    int msec = (((float) interval / 1000) - sec) * 1000;    struct timeval now;    if (gettimeofday(&now, NULL) < 0)    {        swWarn(gettimeofday() failed. Error: %s[%d], strerror(errno), errno);        return SW_ERR;    }    memset(&timer_set, 0, sizeof(timer_set));    timer_set.it_interval.tv_sec = sec;    timer_set.it_interval.tv_usec = msec * 1000;    timer_set.it_value.tv_sec = sec;    timer_set.it_value.tv_usec = timer_set.it_interval.tv_usec;    if (timer_set.it_value.tv_usec > 1e6)    {        timer_set.it_value.tv_usec = timer_set.it_value.tv_usec - 1e6;        timer_set.it_value.tv_sec += 1;    }    if (setitimer(ITIMER_REAL, &timer_set, NULL) < 0)    {        swWarn(setitimer() failed. Error: %s[%d], strerror(errno), errno);        return SW_ERR;    }

Source code explanation:
Split interval into seconds and milliseconds, add two values to timer_set, and then call the setitimer function to set the system timer.

1.5.2.swTimer _ timerfd_set

Statement:

// timer.c 25hstatic int swTimer_timerfd_set(swTimer *timer, int interval);

Function: Call the timerfd function to start the timerfd timer.
Core source code:

    // timer.c 100h    if (timer->fd == 0)    {        timer->fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC);        if (timer->fd < 0)        {            swWarn(timerfd_create() failed. Error: %s[%d], strerror(errno), errno);            return SW_ERR;        }    }    timer_set.it_interval.tv_sec = sec;    timer_set.it_interval.tv_nsec = msec * 1000 * 1000;    timer_set.it_value.tv_sec = now.tv_sec + sec;    timer_set.it_value.tv_nsec = (now.tv_usec * 1000) + timer_set.it_interval.tv_nsec;    if (timer_set.it_value.tv_nsec > 1e9)    {        timer_set.it_value.tv_nsec = timer_set.it_value.tv_nsec - 1e9;        timer_set.it_value.tv_sec += 1;    }    if (timerfd_settime(timer->fd, TFD_TIMER_ABSTIME, &timer_set, NULL) == -1)    {        swWarn(timerfd_settime() failed. Error: %s[%d], strerror(errno), errno);        return SW_ERR;    }

Source code explanation:
Call the timerfd_create function to create a timerfd and assign the value of the returned fd to timer. fd. Then set the value of timer_set and call the timerfd_settime function to set the timer-related attributes.

1.5.3.swTimer _ del

Statement:

// timer.c 26hstatic int swTimer_del(swTimer *timer, int ms);

Function: removes a specified timer from the timer list.
Core source code:

    swHashMap_del_int(timer->list, ms);    return SW_OK;

Source code explanation:
Remove the timer corresponding to ms from the list of timer

1.5.4.swTimer _ free

Statement:

// timer.c 27hstatic void swTimer_free(swTimer *timer);

Function: releases timer memory.
Core source code:

    swHashMap_free(timer->list);    if (timer->use_pipe)    {        timer->pipe.close(&timer->pipe);    }    else if (close(timer->fd) < 0)    {        swSysError(close(%d) failed., timer->fd);    }    if (timer->root)    {        swTimer_node_destory(&timer->root);    }

Source code explanation:
Release the list, close the MPs queue, and release the linked list pointed to by the root user.

1.5.5.swTimer _ add

Statement:

// timer.c 28hstatic int swTimer_add(swTimer *timer, int msec, int interval, void *data);

Function: adds a timer to the timer.
Core source code:

    if (interval == 0)    {        return swTimer_addtimeout(timer, msec, data);    }    swTimer_interval_node *node = sw_malloc(sizeof(swTimer_interval_node));    if (node == NULL)    {        swWarn(malloc failed.);        return SW_ERR;    }    bzero(node, sizeof(swTimer_interval_node));    node->interval = msec;    if (gettimeofday(&node->lasttime, NULL) < 0)    {        swSysError(gettimeofday() failed.);        return SW_ERR;    }    if (msec < timer->interval)    {        int new_interval = swoole_common_divisor(msec, timer->interval);        timer->interval = new_interval;        swTimer_set(timer, new_interval);    }    swHashMap_add_int(timer->list, msec, node, NULL);    timer->num++;

Source code explanation:
If interval is 0, it indicates that the timer is a timeout type timer and calls the swTimer_addtimeout function.
Otherwise, create a swTimer_interval_node struct, set its related attributes, calculate the basic response interval of timer based on interval, and call the swTimer_set function to set a new scheduled interval.
Finally, add the new scheduled task node to the timer list and increase the number of timers by 1.

1.5.6.swTimer _ set

Statement:

// timer.c 29hstatic int swTimer_set(swTimer *timer, int new_interval);

Function: sets the timer response interval of the timer.
Core source code:

    if (SwooleG.use_timerfd)    {        return swTimer_timerfd_set(timer, new_interval);    }    else    {        return swTimer_signal_set(timer, new_interval);    }

Source code explanation:
If timerfd is used, call swTimer_timerfd_set; otherwise, call swTimer_signal_set;

1.5.7.swTimer _ addtimeout

Statement:

// timer.c 30hint swTimer_addtimeout(swTimer *timer, int timeout_ms, void *data);

Function: removes a specified timer from the timer list.
Core source code:

    int new_interval = swoole_common_divisor(timeout_ms, timer->interval);    if (new_interval < timer->interval)    {        swTimer_set(timer, new_interval);        timer->interval = new_interval;    }    struct timeval now;    if (gettimeofday(&now, NULL) < 0)    {        swWarn(gettimeofday() failed. Error: %s[%d], strerror(errno), errno);        return SW_ERR;    }    uint32_t now_ms = now.tv_sec * 1000 + now.tv_usec / 1000;    swTimer_node *node = sw_malloc(sizeof(swTimer_node));    if (node == NULL)    {        swWarn(malloc(%d) failed. Error: %s[%d], (int ) sizeof(swTimer_node), strerror(errno), errno);        return SW_ERR;    }    bzero(node, sizeof(swTimer_node));    node->data = data;    node->exec_msec = now_ms + timeout_ms;    swTimer_node_insert(&timer->root, node);

Source code explanation:
Calculate the minimum time interval of the timer and set the basic response interval of the new timer. Create a new swTimer_node node and set its attribute values. Then, call the swTimer_node_insert function to add a new node to the timer root linked list. (Note that because the timer is one-time, the value of timer-> num is not changed)

1.5.8.swTimer _ select

Statement:

// timer.c 31hint swTimer_select(swTimer *timer);

Function: traverses the timer list to find the timer to respond
Core source code:

    uint64_t key;    swTimer_interval_node *timer_node;    struct timeval now;    if (gettimeofday(&now, NULL) < 0)    {        swSysError(gettimeofday() failed.);        return SW_ERR;    }    //swWarn(%d.%d, now.tv_sec, now.tv_usec);    if (timer->onTimeout == NULL)    {        swWarn(timer->onTimeout is NULL);        return SW_ERR;    }    /**     * timeout task list     */    uint32_t now_ms = now.tv_sec * 1000 + now.tv_usec / 1000;    swTimer_node *tmp = timer->root;    while (tmp)    {        if (tmp->exec_msec > now_ms)        {            break;        }        else        {            timer->onTimeout(timer, tmp->data);            timer->root = tmp->next;            sw_free(tmp);            tmp = timer->root;        }    }    if (timer->onTimer == NULL)    {        swWarn(timer->onTimer is NULL);        return SW_ERR;    }    uint32_t interval = 0;    do    {        //swWarn(timer foreach start----------------------------------------------);        timer_node = swHashMap_each_int(timer->list, &key);        //hashmap empty        if (timer_node == NULL)        {            break;        }        //the interval time(ms)        interval = (now.tv_sec - timer_node->lasttime.tv_sec) * 1000 + (now.tv_usec - timer_node->lasttime.tv_usec) / 1000;        /**         * deviation 1ms         */        if (interval >= timer_node->interval - 1)        {            memcpy(&timer_node->lasttime, &now, sizeof(now));            timer->onTimer(timer, timer_node->interval);        }    } while (timer_node);

Source code explanation:
First, obtain the current system time.
Determines whether the onTimeout callback is set. If not set, an error is returned. Then, traverse the timeout scheduled task list, find the task whose exec_msec time is less than or equal to the current time, call onTimeout to respond to these callbacks, and remove the task.
Determines whether the onTimer callback is set. If not set, an error is returned. Then, traverse the scheduled task list to determine whether the current node needs to respond (current time-lasttime> = interval-1 ms). If a response is required, set a new lasttime and call the onTimer callback.

2. EventTimer2.1.EventTimer Principle

The principle of EventTimer is to use the timeout setting of epoll. By setting the timeout of epoll, you can capture an event after the timeout time. After capturing this event, you can traverse the corresponding event list to learn which events need to be processed.

2.2.EventTimer private operation function 2.2.1.swEventTimer _ add

Statement:

// EventTimer.c 19hstatic int swEventTimer_add(swTimer *timer, int _msec, int interval, void *data);

Function: adds a timer to the timer.
Core source code:
After

    swTimer_node *node = sw_malloc(sizeof(swTimer_node));    if (!node)    {        swSysError(malloc(%d) failed., (int )sizeof(swTimer_node));        return SW_ERR;    }    int now_msec = swEventTimer_get_relative_msec();    if (now_msec < 0)    {        return SW_ERR;    }    node->data = data;    node->exec_msec = now_msec + _msec;    node->interval = interval ? _msec : 0;    swTimer_node_insert(&timer->root, node);

Source code explanation:
Initialize and add a node to the Timer root.

2.2.2.swEventTimer _ del

Statement:

// timer.c 20hstatic int swEventTimer_del(swTimer *timer, int _msec);

Function: removes a specified timer from the timer list.
Core source code:

    if (timer->root)    {        swTimer_node_destory(&timer->root);    }

Source code explanation:
Remove the timer corresponding to ms from the root of timer

2.2.3.swEventTimer _ select

Statement:

// timer.c 21hstatic int swEventTimer_select(swTimer *timer);

Function: select the timer to be responded from the timer.
Core source code:

    uint32_t now_msec = swEventTimer_get_relative_msec();    if (now_msec < 0)    {        return SW_ERR;    }    swTimer_node *tmp = timer->root;    while (tmp)    {        if (tmp->exec_msec > now_msec)        {            break;        }        else        {            if (tmp->interval > 0)            {                timer->onTimer(timer, tmp->interval);            }            else            {                timer->onTimeout(timer, tmp->data);            }            timer->root = tmp->next;            if (timer->root)            {                timer->root->prev = NULL;            }            if (tmp->interval > 0)            {                tmp->exec_msec += tmp->interval;                swTimer_node_insert(&SwooleG.timer.root, tmp);            }            else            {                sw_free(tmp);            }            tmp = timer->root;        }    }    if (timer->root == NULL)    {        SwooleG.main_reactor->timeout_msec = -1;    }    else    {        SwooleG.main_reactor->timeout_msec = timer->root->exec_msec - now_msec;    }

Source code explanation:
Traverse the root linked list. If the node already needs a response (exec_msec is later than the current time), different callback functions are executed based on whether interval is 0. If interval is 0, you also need to remove the current node.
Finally, reset the timeout time of SwooleG. main_reactor. If there is no scheduled task in the timer, it is set to no time-out.

2.2.4.swEventTimer _ free

Statement:

// timer.c 22hstatic void swEventTimer_free(swTimer *timer);

Function: Release timer.
Core source code:

    if (timer->root)    {        swTimer_node_destory(&timer->root);    }

Source code explanation:
Release the timer root linked list

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.