#ifndef LST_TIMER
#define LST_TIMER
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/uio.h>
#include <time.h>
#define BUFFER_SIZE 64
class util_timer;
struct client_data
{
sockaddr_in address;
int sockfd;
char buf[BUFFER_SIZE];
util_timer *timer;
};
class util_timer
{
public:
util_timer() : pre(nullptr), next(nullptr) {}
public:
time_t expire;
void (*cb_func)(client_data *);
client_data *user_data;
util_timer *pre;
util_timer *next;
};
class sort_timer_lst
{
private:
util_timer *head;
util_timer *tail;
public:
sort_timer_lst() : head(nullptr), tail(nullptr) {}
~sort_timer_lst()
{
util_timer *tmp = head;
while (tmp)
{
head = tmp->next;
delete tmp;
tmp = head;
}
}
void add_timer(util_timer *timer)
{
if (timer == nullptr)
{
return;
}
if (head == nullptr)
{
head = tail = timer;
return;
}
if (timer->expire < head->expire)
{
timer->next = head;
timer->pre = nullptr;
head->pre = timer;
head = timer;
return;
}
add_timer(timer, head);
}
void adjust_timer(util_timer *timer)
{
if (timer == nullptr)
{
return;
}
util_timer *tmp = timer->next;
if (tmp == nullptr || timer->expire < tmp->expire)
{
return;
}
if (timer == head)
{
head = head->next;
head->pre = nullptr;
timer->next = nullptr;
add_timer(timer, head);
}
else
{
timer->pre->next = tmp;
tmp->pre = timer->pre;
add_timer(timer, timer->next);
}
}
void del_timer(util_timer *timer)
{
if (timer == nullptr)
{
return;
}
if (timer == head && timer == tail)
{
delete timer;
head = nullptr;
tail = nullptr;
return;
}
if (timer == tail)
{
tail = tail->pre;
tail->next = nullptr;
delete timer;
return;
}
if (timer == head)
{
head = head->next;
head->pre = nullptr;
delete timer;
return;
}
timer->pre->next = timer->next;
timer->next->pre = timer->pre;
delete timer;
}
void tick()
{
if (head == nullptr)
{
return;
}
time_t cur = time(NULL);
util_timer *tmp = head;
while (tmp)
{
if (cur < tmp->expire)
{
break;
}
tmp->cb_func(tmp->user_data);
head = tmp->next;
if (head)
{
head->pre = nullptr;
}
delete tmp;
tmp = head;
}
}
private:
void add_timer(util_timer *timer, util_timer *lst_head)
{
util_timer *prev = lst_head;
util_timer *tmp = prev->next;
while (tmp)
{
if (timer->expire < tmp->expire)
{
prev->next = timer;
timer->pre = prev;
timer->next = tmp;
tmp->pre = timer;
break;
}
prev = tmp;
tmp = tmp->next;
}
if (tmp == nullptr)
{
prev->next = timer;
timer->pre = prev;
timer->next = nullptr;
tail = timer;
}
}
};
#endif
|