简单定时器实现

经常会遇到这样的功能,需要开辟一个线程同时循环的跑一个任务,下面是简单实现的代码

调用select 加超时时间

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

void thread_client_timeout(const void *arg)
{
	int count = 0;
	
	while (1) {
		struct timeval now = {1, 0};
		printf("time out=%d, %u\n", ++count, now.tv_sec);
		
		//.. do something;
		select(0,NULL,NULL,NULL,&now);
	}
}


int main(void)
{
	pthread_t tid_sta_timeout= 0;
	int result;
	void *r;

	result = pthread_create(&tid_sta_timeout, NULL, (void *)thread_client_timeout, NULL);
	if (result != 0) {
		printf("thread_create %d\n", result);
	    return -1;
	}
	pthread_join(tid_sta_timeout, &r);
	printf("finished %u\n", tid_sta_timeout);
}


调用pthread_cond_timedwait 加超时时间

void thread_client_timeout(const void *arg)
{
	pthread_cond_t		cond = PTHREAD_COND_INITIALIZER;
	pthread_mutex_t		cond_mutex = PTHREAD_MUTEX_INITIALIZER;
	int count = 0;
	struct timeval now;
	struct timespec outtime;
	
	while (1) {
		gettimeofday(&now, NULL);
		outtime.tv_sec = now.tv_sec + 1;
		outtime.tv_nsec = now.tv_usec * 1000;
		
		printf("time out=%d, %u\n", ++count, now.tv_sec);
		
		//.. do something;
		pthread_mutex_lock(&cond_mutex);
		pthread_cond_timedwait(&cond, &cond_mutex, &outtime);
		pthread_mutex_unlock(&cond_mutex);		
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值