setitimer函数测试代码1

/*thread1先获取系统时间,然后阻塞,紧接着thread2调用setitimer开启定时器,定时10ms,时间到后收到信号SIGALRM,转到信号处理函数change_semaphore改变信号量,信号量变为1以后thread1停止阻塞,输出两次时间差*/

#include
#include
#include
#include
#include
#include
#include
#include

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()
{
 long int time;
 struct timeval time_start;
 struct timeval time_end;
 gettimeofday((struct timeval*)&time_start,NULL); //get start time and save it to struct
 sem_wait(&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>20000)
 {
  printf("the running time of timer is %d us\n",time);
 }
 exit(0);
}

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

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

int main()
{
 pthread_t id1,id2;
 int ret1,ret2;
 timer1.it_value.tv_usec=10000; //initialize timer
 sem_init(&sem,0,0); //initialize semaphore
 ret1=pthread_create(&id1,NULL,(void*)thread1,NULL); //create thread 1
 ret2=pthread_create(&id2,NULL,(void*)thread2,NULL); //create thread 2
 pthread_join(id1,NULL); //waiting for thread 1 to finish 
 pthread_join(id2,NULL); //waiting for thread 2 to finish 
 return 0;
}

# shell程序
#!/bin/bash
for ((i=0;i<10000;i++));
do 
/root/program/setitimer_test2;
done
#this shell program is used for executing setitimer_test2 for 10000 times

你可能感兴趣的:(Linux应用编程)