免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1245 | 回复: 3
打印 上一主题 下一主题

请教线程条件变量的问题(附代码):等待的信号没有没有收到,但是信号发了 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-07-17 22:25 |只看该作者 |倒序浏览
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mymutex;
pthread_cond_t mycond;

void * func(void * temp)
{
        pthread_mutex_lock(&mymutex);
        write(1, "\nlock", 5);

        pthread_cond_wait(&mymutex, &mycond);
        write(1, "\nwait", 5);
        pthread_mutex_unlock(&mymutex);
        write(1, "\nhi", 3);
        return NULL;
}

int main()
{
        pthread_t tid;
        int a ;

        pthread_mutex_init(&mymutex, NULL);
        pthread_cond_init(&mycond, NULL);

        pthread_create(&tid, NULL, func, NULL);

        sleep(3);
        pthread_cond_signal(&mycond);
        sleep(1);

        write(1, "\n3", 2);

        pthread_mutex_destroy(&mymutex);
        pthread_cond_destroy(&mycond);

        pthread_join(tid, NULL);
}

过程调试发现这样子的现象:
(1)主线程sleep(3);

(2)转到func( ), 在func()中打印"lock ", 然后阻塞在pthread_cond_wait(&mymutex, &mycond);

(3)接着执行主线程main()中的pthread_cond_signal(&mycond), 打印"3";

(4)主线程阻塞与pthread_join(); 一直阻塞 , 不退出shell;

调试发现pthread_cond_signal()返回0即信号函数正确返回,并且信号发送前

pthread_cond_wait(&mymutex, &mycond)正在阻塞;

为什么pthread_cond_wait(&mymutex, &mycond)没有收到发送的信号而还是阻塞在

pthread_cond_wait() 呢? 这样导致了main()最终阻塞与pthread_join().

--------
来不急查资料, 问问这里的大侠们。

谢谢啦, 先 ~~~

论坛徽章:
0
2 [报告]
发表于 2006-07-18 10:56 |只看该作者

回复 1楼 wbyanhust 的帖子

自己顶一个, 怎么没有人回应呢

论坛徽章:
0
3 [报告]
发表于 2006-07-18 11:06 |只看该作者
都1天了还来不及查资料呀?楼主有点懒惰。
编译器报了警告,自己理解吧
pthread_cond_wait(&mymutex, &mycond);

论坛徽章:
0
4 [报告]
发表于 2006-07-18 12:11 |只看该作者
pthread_cond_wait(&mymutex, &mycond);

是啊,楼上的说了答案了,两个参数用反了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP