pthread_cond_timedwait的函数原型:
int pthread_cond_timedwait(pthread_cond_t *cond_interface, pthread_mutex_t * mutex, const timespec *abstime)
abstime是一个绝对时间,Linux中常用的时间结构有struct timespec 和 struct timeval
下面是两个结构的定义
struct timespec
{
time_t tv_sec; /* Seconds. */
long tv_nsec; /* Nanoseconds. */
};
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
两者的区别是:timespec的第二个参数是纳秒数,而timeval的第二个参数是毫秒数。
pthread_cond_timedwait允许线程就阻塞时间设置一个限制值。指定了这个函数必须返回时的系统时间,即使当相对条件下还没有收到信号。
如果发生这种超时情况,此函数返回ETIMEDOUT错误。
使用绝对时间为不是时间差的好处:若函数过早返回(或许因为捕捉了某个信号),那么同一函数无需改变其参数中的timespec结构的内容就能再次被调用。
实例:
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#define MAX_THREAD_NUM 5
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread_fun(void* arg)
{
int index = *(int*)arg;
struct timespec abstime;
struct timeval now;
abstime.tv_sec = now.tv_sec + 5;
abstime.tv_nsec = now.tv_usec * 1000;
printf("[%d]thread start up!\n", index);
pthread_mutex_lock(&mutex);
printf("[%d]thread wait...\n", index);
pthread_cond_timedwait(&cond, &mutex, &abstime);
printf("[%d]thread wake up\n", index);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
pthread_t tid[MAX_THREAD_NUM];
for(int i = 0; i < MAX_THREAD_NUM; i++)
{
pthread_create(&tid[i], NULL, thread_fun, &i);
sleep(1);
}
sleep(3);
pthread_cond_broadcast(&cond);
for(int i = 0; i < MAX_THREAD_NUM; ++i)
{
pthread_join(tid[i], NULL);
}
return 0;
}
运行结果: