谁知道条件变量的用法??用 pthread_cond_timedwait()时遇到了问题

int pthread_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t *mutex, const struct timespec *abstime);

用此函数,没有signal时,线程并没有阻塞abstime ,而是马上返回 ETIMEDOUT 即超时
为什么??
应该怎么用?
谁能给个例子??

谢谢!!
---------------------------------------------------------------

abstime要使用绝对时间,否则可能会出现你所说的情况。

#include

 1<stdio.h>   
 2#include <unistd.h>   
 3#include <pthread.h>   
 4#include <time.h>   
 5  
 6pthread_cond_t mycond;   
 7pthread_mutex_t mymutex;   
 8int mydata;   
 9  
10void *myfun1(void *)   
11{   
12  
13timespec mytime;   
14  
15while(1)   
16{   
17mytime.tv_sec = time(NULL)+1; //Wait for 1 second, Must   
18mytime.tv_nsec = 0;   
19int ret;   
20pthread_mutex_lock(&amp;mymutex);   
21// pthread_cond_wait(&amp;mycond, &amp;mymutex);   
22ret = pthread_cond_timedwait(&amp;mycond, &amp;mymutex,(const struct timespec *)&amp;mytime);   
23  
24if( ret != 0 )   
25{   
26printf("timeout in %d\n",pthread_self());   
27pthread_mutex_unlock(&amp;mymutex);   
28continue;   
29}   
30  
31while(mydata)   
32{   
33printf("consume in %d (mydata = %d)\n",pthread_self(),mydata);   
34mydata--;   
35}   
36pthread_mutex_unlock(&amp;mymutex);   
37}   
38  
39}   
40  
41void *myfun2(void *)   
42{   
43  
44while(1)   
45{   
46pthread_mutex_lock(&amp;mymutex);   
47printf("produce in %d\n",pthread_self());   
48mydata++;   
49pthread_mutex_unlock(&amp;mymutex);   
50pthread_cond_signal(&amp;mycond);   
51sleep(3);   
52}   
53}   
54  
55int main()   
56{   
57mydata = 0;   
58pthread_t mythread1,mythread2,mythread3;   
59  
60pthread_cond_init(&amp;mycond,NULL);   
61pthread_mutex_init(&amp;mymutex,NULL);   
62  
63pthread_create(&amp;mythread1,NULL,myfun1,NULL);   
64pthread_create(&amp;mythread2,NULL,myfun2,NULL);   
65// pthread_create(&amp;mythread3,NULL,myfun1,NULL);   
66// pthread_create(&amp;mythread3,NULL,myfun2,NULL);   
67  
68pthread_join(mythread1,NULL);   
69pthread_join(mythread2,NULL);   
70// pthread_join(mythread3,NULL);   
71  
72return 0;   
73}</time.h></pthread.h></unistd.h></stdio.h>
Published At
Categories with 服务器类
Tagged with
comments powered by Disqus