代码拉取完成,页面将自动刷新
#include <time.h>
#include <string>
#include <pthread.h>
#include <unistd.h> //sleep function
#include <stdlib.h>
#include <iostream>
using namespace std;
struct hased_wheel_timeout{
int round;
int slot_num;
string msg;
int delay_time;
time_t start_time;
struct hased_wheel_timeout *next = NULL;
};
class TimeWheel{
public:
int task_num = 0;
time_t start_time;
static const int N = 10;
struct hased_wheel_timeout *slots[N], *pre_task, *next_task; //This is important
struct hased_wheel_timeout task;
TimeWheel(){
start_time = time(NULL);
for(int i = 0; i < N; i++){
slots[i] = (struct hased_wheel_timeout*)malloc(sizeof(struct hased_wheel_timeout));
}
}
~TimeWheel(){
for(int i = 0; i < N; i++){
struct hased_wheel_timeout* tmp = slots[i];
while(tmp -> next != NULL){
struct hased_wheel_timeout* _free = tmp;
tmp = tmp->next;
free(_free);
}
}
}
void add_task(int delay_time, string s){
time_t cur_time = time(NULL);
time_t dead_time = cur_time + delay_time;// - start_time;
int slot_num = ((long)dead_time) % N;
int round = ((long)dead_time) / N;
struct hased_wheel_timeout* task = (struct hased_wheel_timeout *)malloc(sizeof(struct hased_wheel_timeout));
task -> delay_time = delay_time;
task -> msg = s;
task -> round = round + 1; //for > 0
task -> slot_num = slot_num;
task -> start_time = cur_time;
task -> next = NULL;
cout<<"Add in slot : "<<slot_num<<endl;
struct hased_wheel_timeout* tmp = slots[slot_num];
while(tmp -> next != NULL){
tmp = tmp -> next;
}
tmp -> next = task;
task_num++;
}
void del_task(struct hased_wheel_timeout *pre, struct hased_wheel_timeout *now){
pre -> next = now -> next;
free(now);
}
//the relationship between add_task and run
bool run(){
while(task_num){
time_t cur_time = time(NULL);
int slot_num = ((long)cur_time) % N;
// cout<<"Now in slot : "<<slot_num<<endl;
struct hased_wheel_timeout* point = slots[slot_num];
pre_task = point;
point = point -> next;
while(point != NULL){
point -> round = point -> round - 1;
if(point -> round <= 0){
cout<<"There is a clock for you:"<<endl;
cout<<" "<<point -> msg <<endl;
pre_task -> next = point -> next;
free(point);
point = pre_task ->next;
task_num--;
}else{
pre_task = point;
point = point -> next;
}
}
}
return false;
}
};
struct Msg{
TimeWheel wheel;
int task_num;
};
void* check_time(void *arg){
struct Msg *msg = (struct Msg *)arg;
TimeWheel wheel = msg -> wheel;
int num = msg -> task_num;
while(wheel.run()){
sleep(1);
}
}
int main(){
TimeWheel wheel;
wheel.add_task(2, "This is 2 second message!");
wheel.add_task(10, "This is 10 second message!");
wheel.add_task(5, "This is 5 second message!");
pthread_t thread_handle;
struct Msg msg;
msg.wheel = wheel;
msg.task_num = 3;
pthread_create(&thread_handle, NULL, check_time, &msg);
pthread_join(thread_handle, NULL);
cout<<"pthread id : " << thread_handle <<endl;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。