1
/* $Id: timer.c 4154 2012-06-05 10:41:17Z bennylp $ */
3
* The PJLIB's timer heap is based (or more correctly, copied and modied)
4
* from ACE library by Douglas C. Schmidt. ACE is an excellent OO framework
5
* that implements many core patterns for concurrent communication software.
6
* If you're looking for C++ alternative of PJLIB, then ACE is your best
9
* You may use this file according to ACE open source terms or PJLIB open
10
* source terms. You can find the fine ACE library at:
11
* http://www.cs.wustl.edu/~schmidt/ACE.html
13
* ACE is Copyright (C)1993-2006 Douglas C. Schmidt <d.schmidt@vanderbilt.edu>
16
* This program is free software; you can redistribute it and/or modify
17
* it under the terms of the GNU General Public License as published by
18
* the Free Software Foundation; either version 2 of the License, or
19
* (at your option) any later version.
21
* This program is distributed in the hope that it will be useful,
22
* but WITHOUT ANY WARRANTY; without even the implied warranty of
23
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24
* GNU General Public License for more details.
26
* You should have received a copy of the GNU General Public License
27
* along with this program; if not, write to the Free Software
28
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33
#include <pj/string.h>
34
#include <pj/assert.h>
39
#define THIS_FILE "timer.c"
41
#define HEAP_PARENT(X) (X == 0 ? 0 : (((X) - 1) / 2))
42
#define HEAP_LEFT(X) (((X)+(X))+1)
45
#define DEFAULT_MAX_TIMED_OUT_PER_POLL (64)
49
* The implementation of timer heap.
51
struct pj_timer_heap_t
53
/** Pool from which the timer heap resize will get the storage from */
56
/** Maximum size of the heap. */
59
/** Current size of the heap. */
62
/** Max timed out entries to process per poll. */
63
unsigned max_entries_per_poll;
68
/** Autodelete lock. */
69
pj_bool_t auto_delete_lock;
72
* Current contents of the Heap, which is organized as a "heap" of
73
* pj_timer_entry *'s. In this context, a heap is a "partially
74
* ordered, almost complete" binary tree, which is stored in an
77
pj_timer_entry **heap;
80
* An array of "pointers" that allows each pj_timer_entry in the
81
* <heap_> to be located in O(1) time. Basically, <timer_id_[i]>
82
* contains the slot in the <heap_> array where an pj_timer_entry
83
* with timer id <i> resides. Thus, the timer id passed back from
84
* <schedule_entry> is really an slot into the <timer_ids> array. The
85
* <timer_ids_> array serves two purposes: negative values are
86
* treated as "pointers" for the <freelist_>, whereas positive
87
* values are treated as "pointers" into the <heap_> array.
89
pj_timer_id_t *timer_ids;
92
* "Pointer" to the first element in the freelist contained within
93
* the <timer_ids_> array, which is organized as a stack.
95
pj_timer_id_t timer_ids_freelist;
97
/** Callback to be called when a timer expires. */
98
pj_timer_heap_callback *callback;
104
PJ_INLINE(void) lock_timer_heap( pj_timer_heap_t *ht )
107
pj_lock_acquire(ht->lock);
111
PJ_INLINE(void) unlock_timer_heap( pj_timer_heap_t *ht )
114
pj_lock_release(ht->lock);
119
static void copy_node( pj_timer_heap_t *ht, int slot, pj_timer_entry *moved_node )
123
// Insert <moved_node> into its new location in the heap.
124
ht->heap[slot] = moved_node;
126
// Update the corresponding slot in the parallel <timer_ids_> array.
127
ht->timer_ids[moved_node->_timer_id] = slot;
130
static pj_timer_id_t pop_freelist( pj_timer_heap_t *ht )
132
// We need to truncate this to <int> for backwards compatibility.
133
pj_timer_id_t new_id = ht->timer_ids_freelist;
137
// The freelist values in the <timer_ids_> are negative, so we need
138
// to negate them to get the next freelist "pointer."
139
ht->timer_ids_freelist =
140
-ht->timer_ids[ht->timer_ids_freelist];
146
static void push_freelist (pj_timer_heap_t *ht, pj_timer_id_t old_id)
150
// The freelist values in the <timer_ids_> are negative, so we need
151
// to negate them to get the next freelist "pointer."
152
ht->timer_ids[old_id] = -ht->timer_ids_freelist;
153
ht->timer_ids_freelist = old_id;
157
static void reheap_down(pj_timer_heap_t *ht, pj_timer_entry *moved_node,
158
size_t slot, size_t child)
162
// Restore the heap property after a deletion.
164
while (child < ht->cur_size)
166
// Choose the smaller of the two children.
167
if (child + 1 < ht->cur_size
168
&& PJ_TIME_VAL_LT(ht->heap[child + 1]->_timer_value, ht->heap[child]->_timer_value))
171
// Perform a <copy> if the child has a larger timeout value than
173
if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, moved_node->_timer_value))
175
copy_node( ht, slot, ht->heap[child]);
177
child = HEAP_LEFT(child);
180
// We've found our location in the heap.
184
copy_node( ht, slot, moved_node);
187
static void reheap_up( pj_timer_heap_t *ht, pj_timer_entry *moved_node,
188
size_t slot, size_t parent)
190
// Restore the heap property after an insertion.
194
// If the parent node is greater than the <moved_node> we need
196
if (PJ_TIME_VAL_LT(moved_node->_timer_value, ht->heap[parent]->_timer_value))
198
copy_node(ht, slot, ht->heap[parent]);
200
parent = HEAP_PARENT(slot);
206
// Insert the new node into its proper resting place in the heap and
207
// update the corresponding slot in the parallel <timer_ids> array.
208
copy_node(ht, slot, moved_node);
212
static pj_timer_entry * remove_node( pj_timer_heap_t *ht, size_t slot)
214
pj_timer_entry *removed_node = ht->heap[slot];
216
// Return this timer id to the freelist.
217
push_freelist( ht, removed_node->_timer_id );
219
// Decrement the size of the heap by one since we're removing the
224
removed_node->_timer_id = -1;
226
// Only try to reheapify if we're not deleting the last entry.
228
if (slot < ht->cur_size)
231
pj_timer_entry *moved_node = ht->heap[ht->cur_size];
233
// Move the end node to the location being removed and update
234
// the corresponding slot in the parallel <timer_ids> array.
235
copy_node( ht, slot, moved_node);
237
// If the <moved_node->time_value_> is great than or equal its
238
// parent it needs be moved down the heap.
239
parent = HEAP_PARENT (slot);
241
if (PJ_TIME_VAL_GTE(moved_node->_timer_value, ht->heap[parent]->_timer_value))
242
reheap_down( ht, moved_node, slot, HEAP_LEFT(slot));
244
reheap_up( ht, moved_node, slot, parent);
250
static void grow_heap(pj_timer_heap_t *ht)
252
// All the containers will double in size from max_size_
253
size_t new_size = ht->max_size * 2;
254
pj_timer_id_t *new_timer_ids;
257
// First grow the heap itself.
259
pj_timer_entry **new_heap = 0;
261
new_heap = (pj_timer_entry**)
262
pj_pool_alloc(ht->pool, sizeof(pj_timer_entry*) * new_size);
263
memcpy(new_heap, ht->heap, ht->max_size * sizeof(pj_timer_entry*));
264
//delete [] this->heap_;
267
// Grow the array of timer ids.
270
new_timer_ids = (pj_timer_id_t*)
271
pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t));
273
memcpy( new_timer_ids, ht->timer_ids, ht->max_size * sizeof(pj_timer_id_t));
275
//delete [] timer_ids_;
276
ht->timer_ids = new_timer_ids;
278
// And add the new elements to the end of the "freelist".
279
for (i = ht->max_size; i < new_size; i++)
280
ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
282
ht->max_size = new_size;
285
static void insert_node(pj_timer_heap_t *ht, pj_timer_entry *new_node)
287
if (ht->cur_size + 2 >= ht->max_size)
290
reheap_up( ht, new_node, ht->cur_size, HEAP_PARENT(ht->cur_size));
295
static pj_status_t schedule_entry( pj_timer_heap_t *ht,
296
pj_timer_entry *entry,
297
const pj_time_val *future_time )
299
if (ht->cur_size < ht->max_size)
301
// Obtain the next unique sequence number.
303
entry->_timer_id = pop_freelist(ht);
304
entry->_timer_value = *future_time;
305
insert_node( ht, entry);
313
static int cancel( pj_timer_heap_t *ht,
314
pj_timer_entry *entry,
317
long timer_node_slot;
321
// Check to see if the timer_id is out of range
322
if (entry->_timer_id < 0 || (pj_size_t)entry->_timer_id > ht->max_size)
325
timer_node_slot = ht->timer_ids[entry->_timer_id];
327
if (timer_node_slot < 0) // Check to see if timer_id is still valid.
330
if (entry != ht->heap[timer_node_slot])
332
pj_assert(entry == ht->heap[timer_node_slot]);
337
remove_node( ht, timer_node_slot);
340
// Call the close hook.
341
(*ht->callback)(ht, entry);
348
* Calculate memory size required to create a timer heap.
350
PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count)
352
return /* size of the timer heap itself: */
353
sizeof(pj_timer_heap_t) +
354
/* size of each entry: */
355
(count+2) * (sizeof(pj_timer_entry*)+sizeof(pj_timer_id_t)) +
356
/* lock, pool etc: */
361
* Create a new timer heap.
363
PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool,
365
pj_timer_heap_t **p_heap)
370
PJ_ASSERT_RETURN(pool && p_heap, PJ_EINVAL);
377
/* Allocate timer heap data structure from the pool */
378
ht = PJ_POOL_ALLOC_T(pool, pj_timer_heap_t);
382
/* Initialize timer heap sizes */
385
ht->max_entries_per_poll = DEFAULT_MAX_TIMED_OUT_PER_POLL;
386
ht->timer_ids_freelist = 1;
391
ht->auto_delete_lock = 0;
393
// Create the heap array.
394
ht->heap = (pj_timer_entry**)
395
pj_pool_alloc(pool, sizeof(pj_timer_entry*) * size);
399
// Create the parallel
400
ht->timer_ids = (pj_timer_id_t *)
401
pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size);
405
// Initialize the "freelist," which uses negative values to
406
// distinguish freelist elements from "pointers" into the <heap_>
408
for (i=0; i<size; ++i)
409
ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
415
PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht )
417
if (ht->lock && ht->auto_delete_lock) {
418
pj_lock_destroy(ht->lock);
423
PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht,
427
if (ht->lock && ht->auto_delete_lock)
428
pj_lock_destroy(ht->lock);
431
ht->auto_delete_lock = auto_del;
435
PJ_DEF(unsigned) pj_timer_heap_set_max_timed_out_per_poll(pj_timer_heap_t *ht,
438
unsigned old_count = ht->max_entries_per_poll;
439
ht->max_entries_per_poll = count;
443
PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry,
446
pj_timer_heap_callback *cb )
448
pj_assert(entry && cb);
450
entry->_timer_id = -1;
452
entry->user_data = user_data;
459
PJ_DEF(pj_status_t) pj_timer_heap_schedule_dbg( pj_timer_heap_t *ht,
460
pj_timer_entry *entry,
461
const pj_time_val *delay,
462
const char *src_file,
465
PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,
466
pj_timer_entry *entry,
467
const pj_time_val *delay)
473
PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL);
474
PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL);
476
/* Prevent same entry from being scheduled more than once */
477
PJ_ASSERT_RETURN(entry->_timer_id < 1, PJ_EINVALIDOP);
480
entry->src_file = src_file;
481
entry->src_line = src_line;
483
pj_gettickcount(&expires);
484
PJ_TIME_VAL_ADD(expires, *delay);
487
status = schedule_entry(ht, entry, &expires);
488
unlock_timer_heap(ht);
493
PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,
494
pj_timer_entry *entry)
498
PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL);
501
count = cancel(ht, entry, 1);
502
unlock_timer_heap(ht);
507
PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,
508
pj_time_val *next_delay )
513
PJ_ASSERT_RETURN(ht, 0);
515
if (!ht->cur_size && next_delay) {
516
next_delay->sec = next_delay->msec = PJ_MAXINT32;
521
pj_gettickcount(&now);
524
while ( ht->cur_size &&
525
PJ_TIME_VAL_LTE(ht->heap[0]->_timer_value, now) &&
526
count < ht->max_entries_per_poll )
528
pj_timer_entry *node = remove_node(ht, 0);
531
unlock_timer_heap(ht);
533
(*node->cb)(ht, node);
536
if (ht->cur_size && next_delay) {
537
*next_delay = ht->heap[0]->_timer_value;
538
PJ_TIME_VAL_SUB(*next_delay, now);
539
if (next_delay->sec < 0 || next_delay->msec < 0)
540
next_delay->sec = next_delay->msec = 0;
541
} else if (next_delay) {
542
next_delay->sec = next_delay->msec = PJ_MAXINT32;
544
unlock_timer_heap(ht);
549
PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht )
551
PJ_ASSERT_RETURN(ht, 0);
556
PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht,
557
pj_time_val *timeval)
559
pj_assert(ht->cur_size != 0);
560
if (ht->cur_size == 0)
564
*timeval = ht->heap[0]->_timer_value;
565
unlock_timer_heap(ht);
571
PJ_DEF(void) pj_timer_heap_dump(pj_timer_heap_t *ht)
575
PJ_LOG(3,(THIS_FILE, "Dumping timer heap:"));
576
PJ_LOG(3,(THIS_FILE, " Cur size: %d entries, max: %d",
577
(int)ht->cur_size, (int)ht->max_size));
583
PJ_LOG(3,(THIS_FILE, " Entries: "));
584
PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource"));
585
PJ_LOG(3,(THIS_FILE, " ----------------------------------"));
587
pj_gettickcount(&now);
589
for (i=0; i<(unsigned)ht->cur_size; ++i) {
590
pj_timer_entry *e = ht->heap[i];
593
if (PJ_TIME_VAL_LTE(e->_timer_value, now))
594
delta.sec = delta.msec = 0;
596
delta = e->_timer_value;
597
PJ_TIME_VAL_SUB(delta, now);
600
PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d",
602
(int)delta.sec, (int)delta.msec,
603
e->src_file, e->src_line));
607
unlock_timer_heap(ht);