函數聲明:int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);
其中abstime是絕對系統時間
代碼如下:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
struct node
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int data;
};
int t=0;
void *thr_timer(void *arg)
{
t++;
struct timespec timer;
timer.tv_sec=time(NULL)+1;
timer.tv_nsec=0;
struct node *pnode=(struct node*)arg;
pthread_mutex_lock(&(pnode->mutex));
printf("lock\n");
int ret;
while(pnode->data==0)
{
ret=pthread_cond_timedwait(&(pnode->cond),&(pnode->mutex),&timer);
if(ret==ETIMEDOUT)
{
printf("time out\n");
break;
}
}
pthread_mutex_unlock(&(pnode->mutex));
printf("%d time thread end\n",t);
return ((void*)0);
}
int main()
{
struct node *snode=(struct node*)malloc(sizeof(struct node));
pthread_mutex_init(&(snode->mutex),NULL);
pthread_cond_init(&(snode->cond),NULL);
snode->data=0;
pthread_t tid;
pthread_create(&tid,NULL,thr_timer,(void*)snode);
snode->data++;
sleep(2);
if(snode->data>0)
pthread_cond_signal(&(snode->cond));
snode->data=0;
pthread_create(&tid,NULL,thr_timer,(void*)snode);
// sleep(20);
//snode->data++;
//pthread_cond_signal(&(snode->cond));
sleep(200);
free(snode);
return 0;
}