基于多线程的定时器程序,该定时器主要定时事件在回调函数中实现

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>

typedef void (*timer_callback)();

/*定时器参数*/
typedef struct
{
	unsigned int interval_time; 		/* 时间间隔,单位秒 */
	timer_callback func; 			/* 处理函数 */
}timer_para;

int i = 1;

void timer_callback_func()
{
	printf("timer print %d second
",i*5);
	i++;

}

/*定时器处理线程*/
void start_timer(void *argv)
{
	struct itimerval tick;
    
	timer_para time_val = {0};
	time_val.interval_time = 5;
	time_val.func = timer_callback_func;

	pthread_detach(pthread_self());
		
	printf("AppStartTimer start!
");
	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!
");
	}
	
	while(1)
	{
		pause();
	}

	printf("AppStartTimer exit!
");
}

int main()
{
    int ret = -1;
	pthread_t timerid;
	
	ret=pthread_create(&timerid,NULL,(void *)start_timer, NULL); 
	if(0 != ret)
	{
		printf("create AppProcessTimer failed!ret=%d err=%s
",ret, strerror(ret));
	}
	
	 //主进程进入循环休眠中,数据处理主要在回调函数
	while(1)
	{
		sleep(9999);
	}

	return 0;
}

  

原文地址:https://www.cnblogs.com/porkerface/p/12397015.html