- 爱易网页
-
Linux
- pthread_cond_timedwait带时间的线程同步条件变量用法,请问!多谢
日期:2014-05-16 浏览次数:20801 次
pthread_cond_timedwait带时间的线程同步条件变量用法,请教!谢谢
子线程的部分代码如下:
struct timespec timeout;
int status;
time_t tmp;
while(1)
{
time(&tmp);
printf( "time = %d\n ",tmp);
printf( "this time is %s ",ctime(&tmp));
timeout.tv_sec = tmp + 10;
timeout.tv_nsec = 0;
printf( "timeout.tv_sec = %d\n ",timeout.tv_sec);
pthread_mutex_lock(&mutex);
status = pthread_cond_timedwait (&cond, &mutex, &timeout);
pthread_mutex_unlock(&mutex);
sleep(1);
}
----------------------------------
系统时钟正常。
没有线程在调用函数是条件变量 cond有效,因此
status = pthread_cond_timedwait (&cond, &mutex, &timeout);
要阻塞等待10秒后由于超时而返回,但是此函数却是立即返回的。
且返回值 有时为 553250有时为-11532016。errno=2.
请问该怎么修改代码才能正常使用status = pthread_cond_timedwait (&cond, &mutex, &timeout);
这个带超时时间的条件等待函数。谢谢
------解决方案--------------------
abstime要使用绝对时间,否则可能会出现你所说的情况。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
pthread_cond_t mycond;
pthread_mutex_t mymutex;
int mydata;
void *myfun1(void *)
{
timespec mytime;
while(1)
{
mytime.tv_sec = time(NULL)+1; //Wait for 1 second, Must
mytime.tv_nsec = 0;
int ret;
pthread_mutex_lock(&mymutex);
// pthread_cond_wait(&mycond, &mymutex);
ret = pthread_cond_timedwait(&mycond, &mymutex,(const struct timespec *)&mytime);
if( ret != 0 )
{
printf( "timeout in %d\n ",pthread_self());
pthread_mutex_unlock(&mymutex);
continue;
}
while(mydata)
{
printf( "consume in %d (mydata = %d)\n ",pthread_self(),mydata);
mydata--;
}
pthread_mutex_unlock(&mymutex);
}
}
void *myfun2(void *)
{
while(1)