Linux 下定时器的实现方式分析(6)

清单 10. pjlib 提供的基于最小堆的定时器接口

/**

* Create a timer heap.

*/

PJ_DECL(pj_status_t) pj_timer_heap_create( pj_pool_t *pool,

pj_size_t count,

pj_timer_heap_t **ht);

/**

* Destroy the timer heap.

*/

PJ_DECL(void) pj_timer_heap_destroy( pj_timer_heap_t *ht );

/**

* Initialize a timer entry. Application should call this function at least

* once before scheduling the entry to the timer heap, to properly initialize

* the timer entry.

*/

PJ_DECL(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry,

int id,

void *user_data,

pj_timer_heap_callback *cb );

/**

* Schedule a timer entry which will expire AFTER the specified delay.

*/

PJ_DECL(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,

pj_timer_entry *entry,

const pj_time_val *delay);

/**

* Cancel a previously registered timer.

*/

PJ_DECL(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,

pj_timer_entry *entry);

/**

* Poll the timer heap, check for expired timers and call the callback for

* each of the expired timers.

*/

PJ_DECL(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,

pj_time_val *next_delay);

pjlib 中的定时器在内部使用数组的方式实现堆,这样对于内存空间的使用将更加的紧凑;它的实现还可在定时器的数量超过预先设定的最大数量时会自己增加最大定时器数量。文件 pjlib/src/pjlib-test/timer.c 是它的一个单元测试。与基于链表方式的实现相比较,明显它的时间复杂度要低一些,这样可以支持更多的定时器实例。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpfxs.html