免费网络  

 

使用定时器轮, 先讲主程序

void* tmr_mgmt_thread(void *arg)
{
    int slot = 0;
    list_header *tmr_list;
    list_head *element, *svd_elem;
    p_timer_t *tmr;
    unsigned int svd_tick, cur_tick, delta_tick;

    _UNUSED_(arg);
    while (tmr_mgmt_keep_run == FALSE) {
        //TODO, if close this application fast enough, this thread will hung here
        sleep(1);
    }

    tmr_mgmt_running = TRUE;
    svd_tick = GetTickCount();
    while (tmr_mgmt_keep_run) {
        usleep(10);
        cur_tick = GetTickCount();
        delta_tick = cur_tick - svd_tick;
        svd_tick = cur_tick;

        pthread_mutex_lock(&tmr_mutex);
        while (delta_tick--) {
            tmr_list = &wheel[0][slot].timer_list;
            slot = (slot + 1) % WHEEL_ELEM;
            list_for_each(tmr_list, element) {
                tmr = list_entry(element, p_timer_t, list);
                if (tmr->locked) {
                    continue;
                }
                svd_elem = element->prev;
                list_delink(tmr_list, element);
                tmr->timer_cb(tmr, tmr->app_context);
                tmr->locked = TRUE;
                if (tmr->period_ms == 0) {
                    my_free(tmr, TIMER_MEM);
                } else {
                    p_timer_start(tmr->period_ms, tmr->timer_cb, tmr->app_context);
                }
                element = svd_elem;
            }
            update_timer_wheel(slot);
        }
        pthread_mutex_unlock(&tmr_mutex);
    }

    tmr_mgmt_running = FALSE;
    return NULL;
}

posted on 2010-08-16 20:16  jundai  阅读(298)  评论(0)    收藏  举报