我想实现一个类似于游戏引擎中的定时器的功能
首先 创建定时器,返回定时器id,然后,启动定时器(定时器id,回调函数)
2、废话不多说,先贴代码
多线程的头文件 process.h
#pragma once
#include
typedef struct
{
unsigned int id;
int timeout; //毫秒
}S_Timer;
#define MAXNUM 256
static S_Timer TimerList[256] = { 0 };
int initTimer(S_Timer* timer, int timeout)
{
if (!timer || timeout < 0) return false;
timer->timeout = timeout;
for (int i = 0; i < MAXNUM; i++)
{
if (TimerList[i].id == 0)
{
timer->id = i;
TimerList[i] = *timer;
return i;
}
}
return -1;
}
void killTimer(int timerID)
{
TimerList[timerID].id = 0;
TimerList[timerID].timeout = 0;
}
typedef void(*timerProcessFunc)(void*);
#include
typedef struct {
clock_t start;
int timerID;
timerProcessFunc timerapp;
}CANSHU;
void fun_count(void*lp) {
CANSHU *p = (CANSHU*)lp;
clock_t finish;
double totaltime;
while (1)
{
finish = clock();
totaltime = (double)(finish - p->start);
if (totaltime >= TimerList[p->timerID].timeout)
{
p->timerapp(&totaltime);
std::cout << "asdasd" << totaltime;
break;
}
}
}
void startTimer(int timerID, timerProcessFunc timerapp)
{
clock_t start, finish;
double totaltime;
start = clock();
CANSHU canshu;
canshu.start = start;
canshu.timerID = timerID;
canshu.timerapp = timerapp;
_beginthread(fun_count, 0,(void*)&canshu);
/**********计时开始*****************/
_endthread();
/********************************/
}
void timerProcess(void* userPara) //回调函数
{
std::cout << "定时了" << *(double*)userPara << "毫秒" << std::endl;
}
#include
int main() {
S_Timer *timer1 = (S_Timer*)malloc(sizeof(S_Timer));
int id = initTimer(timer1, 1000);
if (id != -1) {
startTimer(id, timerProcess);
}
while (1) {
if (a >= 10) {
printf("主线程执行完毕
");
break;
}
}
system("pause");
return 0;
}
上面的代码是我结合一个网上定时器的创建和我添加了多线程。
暂时我对传入多参数的方法 就只有用结构体 + 类型转换来实现。