免费注册 查看新帖 |

Chinaunix

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

[C] 请教pthread_cond_wait的一个问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-22 00:09 |只看该作者 |倒序浏览
20可用积分
我看到下面一段多线程的小程序。这个程序创建两个线程,都检查一个变量,符合条件就继续执行。程序启动以后,先后执行了thread1和thread2.

我的问题是
1. pthread_cond_wait在thread1中到底被执行了多少次? 是一次还是无数次? 从执行结果来看是1次,但是既然是在while循环的内部,那么应该是执行了无数次才对吧? 难道pthread_cond_wait会用阻塞的方式去监视Number变量?
    我不能理解那个while循环是如何工作的。

2. thread1和thread2的执行顺序是固定的呢还是随机的呢?

谢谢,源代码如下:
----------------------------------------
#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

using namespace std;

int Number = 0;
pthread_mutex_t NMutex;
pthread_cond_t NCond;

void *thread1(void *arg)
{
        pthread_detach(pthread_self());
        pthread_mutex_lock(&NMutex);
        while (Number <= 0 ){
                cout<<"t1"<<endl;
                pthread_cond_wait(&NCond, &NMutex);
        }
        int Count = Number;
        int Sum = 1;
        for (int i = 1; i < Count; i++)
                Sum += i;
        cout << "count by thread1 is " << Sum << endl;
        pthread_mutex_unlock(&NMutex);
        return NULL;
}

void *thread2(void *arg)
{
        pthread_detach(pthread_self());
        pthread_mutex_lock(&NMutex);
        while (Number <= 0 )//等待主线程读入Number
                pthread_cond_wait(&NCond, &NMutex);
        int Count = Number;
        int Sum = 1;
        for (int i = 1; i < Count; i++)
                Sum += i;
        cout << "count by thread2 is " << Sum << endl;
        pthread_mutex_unlock(&NMutex);
        return NULL;
}

int main(int argc, char* argv[])
{
        pthread_mutex_init(&NMutex, NULL);
        pthread_cond_init(&NCond, NULL);
        pthread_t p1, p2;
        pthread_create(&p1, NULL, thread1, NULL);
        pthread_create(&p2, NULL, thread2, NULL);
//begin input
        pthread_mutex_lock(&NMutex);
           cout << "input a number ";
        cin >> Number;
        pthread_mutex_unlock(&NMutex);
        pthread_cond_signal(&NCond);
//end input

        pthread_exit(NULL);
}

最佳答案

查看完整内容

1.pthread_cond_wait确实是阻塞方式的,它是用pthread_cond_signal来唤醒的撒。whiile循环中的原理就是取得互斥量,如果符合whiile的条件,进入循环,释放互斥量,阻塞在pthread_cond_wait。被pthread_cond_signal唤醒后,继续程序流程,再次检查while的条件,如此。。。2.随即的

论坛徽章:
0
2 [报告]
发表于 2009-11-22 00:09 |只看该作者

回复 #1 jeanlove 的帖子

1.pthread_cond_wait确实是阻塞方式的,它是用pthread_cond_signal来唤醒的撒。

whiile循环中的原理就是取得互斥量,如果符合whiile的条件,进入循环,释放互斥量,阻塞在pthread_cond_wait。

被pthread_cond_signal唤醒后,继续程序流程,再次检查while的条件,如此。。。

2.随即的

论坛徽章:
0
3 [报告]
发表于 2009-11-23 01:04 |只看该作者
这里可以用pthread_join,来固定顺序么???

[ 本帖最后由 firefoxmmx 于 2009-11-23 01:08 编辑 ]

论坛徽章:
0
4 [报告]
发表于 2010-07-16 23:54 |只看该作者
pthread_cond_wait()有虚假唤醒的情况,也就是说不满足唤醒条件,也被唤醒了,所以要再判断一下条件是否满足
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP