学习笔记之定时器

定时器

1. 结构体详解

  • timer_t :timerid 定时器ID;
  • struct sigevent sev;
  • struct itimerspec it;
struct sigevent 
{	
	int sigev_notify; //通知方法
	int sigev_signo; //信号类别 
	union sigval sigev_value; //通过通知传递的数据 下有详解
	void (*sigev_notify_function)(union sigval); //用于线程运行的函数
	void *sigev_notify_attributes; //上面那个线程的属性
	pid_t sigev_notify_thread_id; //线程id
}

union sigval //通过通知传递的数据
{
	int sival_int;
	void *sival_ptr;
}
struct itimerspec 
{	
	struct timespec it_interval;  //循环时间
	struct timespec it_value;	//初次到期的时间间隔  就是延迟多长时间开始
}
	it.it_interval.tv_sec=1;//时间s
	it.it_interval.tv_nsec=0;//纳秒us.
	it.it_value.tv_sec=0;
	it.it_value.tv_nsec=0;
	

sev->sigev_notify :

  • SIGEV_SIGNAL: 发送由sev->sigev_signo指定的信号到调用进程,sigev_signo此时指定信号的类别
  • SIGEV_NONE: 什么都不做,只提供通过timer_gettime和timer_getoverrun查询超时信息。
  • SIGEV_THREAD:以sev->sigev_notification_attributes为线程属性创建一个线程, 在新建的线程内部以sev->sigev_value为参数调用evp->sigev_notification_function
    ~~说白了就是每次创建一个新线程,用线程运行sigev_notify_function函数,传入sigev_value作为参数,每次sigev_value修改可以改变定时发送的数据 ~~
  • SIGEV_THREAD_ID: 发送sev->sigev_signo到sev->sigev_notify_thread_id指定线程id,该线程实际存在且属于当前的调用进程。

sev->sigev_signo :

  • 可靠信号与不可靠信号,实时信号与非实时信号
    • 可靠信号就是实时信号 : 信号支持排队,不会丢失,发多少次,就可以收到多少次
    • 不可靠信号就是非实时信号:信号不支持排队,信号可能会丢失,发送多次相同信号,进程只接收一次
    • [SIGRTMIN,SIGRTMAX]区间内的都是可靠信号
    • 一般可填可不填,不太懂

timer_create: 与配置绑定

define CLOCKID CLOCK_REALTIME
if(timer_create(CLOCKID,&sev,&timerid)==-1)//定时器ID与sev结构体绑定
{
	perror("fail to timer_create");
	exit(-1);
}

timer_settime: 与时间绑定

		if(timer_settime(timerid,0,&it,NULL)==-1)
		{
			perror("fail to timer_settime");
			exit(-1);
		}

使用案例:

	 timer_t timerid
	 struct sigevent sev;  
	 struct itimerspec its;  
	 sev.sigev_notify = SIGEV_THREAD;  
	 sev.sigev_signo = SIGRTMIN;  
	 sev.sigev_value.sival_ptr = timerid;
	 sev.sigev_value.sival_int=2
	 sev.sigev_notify_function = send_dog;
	 sev.sigev_notify_attributes = NULL;  
	 if(timer_create(CLOCK_REALTIME,&sev,&timerid)==-1)
	{
		perror("fail to timer_create");
		exit(-1);
	}
	 its.it_value.tv_nsec=10;
	 its.it_value.tv_sec=0;
	 its.it_interval.tv_sec =1;  
	 its.it_interval.tv_nsec =0;  
	 if(timer_settime(timerid, 0, &its, NULL) == -1)  
	 {  
			perror("fail to timer_settime");
			exit(-1);
	 } 

void send_dog(union sigval v)
{
	cout<<"test:"<<v.sival_int<<endl;
}
原创文章 23 获赞 26 访问量 438

猜你喜欢

转载自blog.csdn.net/weixin_41672404/article/details/105729262