经常会遇到这样的功能,需要开辟一个线程同时循环的跑一个任务,下面是简单实现的代码
调用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);
}
}