您的位置:首页 > 运维架构 > Linux

Linux setitimer函数测试代码2

2014-03-11 08:45 246 查看
/*首先提示用户输入上限值,然后thread1和thread2循环检测定时器定时时间,直至60秒后,thread3醒来,输出定时器超过设定上限值的次数,并结束程序。*/

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

int upper_limit;
int times=0;
void change_semaphore();

struct sem_t
{
long int sem1;
};
struct sem_t sem; // define a struct of semaphore

struct itimerval timer1; //define a struct which will be used by function setitimer

void thread1()
{
int i;
long int time;
struct timeval time_start;
struct timeval time_end;
while(1)
{
gettimeofday((struct timeval*)&time_start,NULL); //get start time and save it to struct
sem_wait((struct sem_t*)&sem); //block the present thread till semaphore is bigger than zero
gettimeofday((struct timeval*)&time_end,NULL); //get end time and save it to struct
time=time_end.tv_usec-time_start.tv_usec; //calculate the running time of timer
if(time>upper_limit)
{
times++;
printf("the running time of timer is %d us\n",time);
}
}
}

void thread2()
{
setitimer(ITIMER_REAL,&timer1,NULL); //turn on timer
signal(SIGALRM,change_semaphore); //register signal SIGALRM to function change_semaphore
while(1)
{
pause();//waiting for signal SIGALRM
}
}

void thread3()
{
sleep(60);
printf("Setitimer test is over !\n");
printf("The timer ran over upper limit for %d times\n",times);
}

void change_semaphore()
{
sem_post((struct sem_t*)&sem); //semaphore adds one
}

int main()
{
int i;
pthread_t id1,id2,id3;
int ret1,ret2,ret3;
printf("Please input upper limit(us)\n");
scanf("%d",&upper_limit); //input upper limit
timer1.it_value.tv_usec=10000; //initialize timer
timer1.it_interval.tv_usec=10000; //initialize timer
sem_init((struct sem_t*)&sem,0,0); //initialize semaphore
ret2=pthread_create(&id2,NULL,(void*)thread2,NULL); //create thread 2
if(ret2==0)
printf("Created thread 2 successfully !\n");
else
printf("Failed to create thread 2 !\n");
ret1=pthread_create(&id1,NULL,(void*)thread1,NULL); //create thread 1
if(ret1==0)
printf("Created thread 1 successfully !\n");
else
printf("Failed to create thread 1 !\n");
ret3=pthread_create(&id3,NULL,(void*)thread3,NULL); //create thread 3
if(ret3==0)
printf("Created thread 3 successfully !\n");
else
printf("Failed to create thread 3 !\n");
pthread_join(id3,NULL); //wait for thread 3 to finish
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: