c语言设置线程自动回收,C语言 创建自己的使用线程的定时器

b473c6233e933feb77a9404a913e74bc.png

我想实现一个类似于游戏引擎中的定时器的功能

首先   创建定时器,返回定时器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;

}

上面的代码是我结合一个网上定时器的创建和我添加了多线程。

暂时我对传入多参数的方法 就只有用结构体 + 类型转换来实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值