C语⾔-多线程定时器(基于回调函数)基于多线程的定时器程序,该定时器主要定时事件在回调函数中实现。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/time.h>
#include<signal.h>
#include<pthread.h>
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long u64;
typedef void(*timer_callback)();
/*定时器参数*/
typedef struct
{
u32 interval_time;/* 时间间隔,单位秒 */
timer_callback func;/* 处理函数 */
}timer_para;
int i =1;
/*定时器处理线程*/
void start_timer(void*argv)
{
struct itimerval tick;
timer_para * time_val;
time_val =(timer_para *)argv;
pthread_detach(pthread_self());
printf("AppStartTimer start!\n");
signal(SIGALRM, time_val->func);
memset(&tick,0,sizeof(tick));
//Timeout to run first time
tick.it_value.tv_sec = time_val->interval_time;
端午节快乐祝福语简短tick.it_value.tv_usec =0;
//After first, the Interval time for clock
tick.it_interval.tv_sec = time_val->interval_time;
tick.it_interval.tv_usec =0;
if(setitimer(ITIMER_REAL,&tick,NULL)<0)
{
printf("Set timer failed!\n");
}
while(1)
{
pause();
}
printf("AppStartTimer exit!\n");
}
int timer_create(timer_para *time_val)
{
int ret =-1;人民检察院是国家的什么机关
int ret =-1;
pthread_t timerid;
ret=pthread_create(&timerid,NULL,(void*)start_timer,time_val);
if(0!= ret)
{
重阳节的意义是什么吃什么printf("create AppProcessTimer failed!ret=%d err=%s\n",ret,strerror(ret)); }
return ret;
}
void timer_callback_func()
{
printf("timer print %d second\n",i*10);
i++;
}
int main()
{
timer_para time_val ={0};父亲节祝福语精选
printf("main thread-----\n");
//timer thread
time_val.interval_time =10;
time_val.func = timer_callback_func;
短发型图片timer_create(&time_val);
//主进程进⼊循环休眠中,数据处理主要在回调函数
while(1)
{
sleep(9999);
}广东温泉哪里好
return0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论