相比较时间轮,时间堆的效率更高,主要利用最小堆的思想实现。
具体实现过程如下:
#ifndef intIME_HEAP
#define intIME_HEAP
#include <iostream>
#include <netinet/in.h>
#include <time.h>
using std::exception;
#define BUFFER_SIZE 64
class heap_timer;
struct client_data
{
sockaddr_in address;
int sockfd;
char buf[ BUFFER_SIZE ];
heap_timer* timer;
};
class heap_timer
{
public:
heap_timer( int delay )
{
expire = time( NULL ) + delay;
}
public:
time_t expire;
void (*cb_func)( client_data* );
client_data* user_data;
};
class time_heap
{
public:
time_heap( int cap ) throw ( std::exception )
: capacity( cap ), cur_size( 0 )
{
array = new heap_timer* [capacity];
if ( ! array )
{
throw std::exception();
}
for( int i = 0; i < capacity; ++i )
{
array[i] = NULL;
}
}
time_heap( heap_timer** in