天天看點

Linux setitimer函數測試代碼2

#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; }

繼續閱讀