setitimer函数测试代码1

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

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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值