免费注册 查看新帖 |

Chinaunix

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

[C] 多线程编程,mutex与condition [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-04-29 21:24 |只看该作者 |倒序浏览
#include <stdio.h>
#include <pthread.h>
#include "stdlib.h"

pthread_cond_t cond;
pthread_mutex_t mutex;
void thread()
{
    pthread_mutex_lock(&mutex);
    int i;
    pthread_cond_wait(&cond,&mutex);
    for(i=0;i<5;i++)
    {   
            printf("This is a pthread %u.\n",pthread_self());
    }   
    pthread_mutex_unlock(&mutex);
}
void thread2()
{
        int i;
        for(i=0;i<5;++i)
        {   
                printf("This is thread2 %u,\n",pthread_self());
                sleep(1);
        }   
        pthread_cond_broadcast(&cond);
}
int main(void)
{
    pthread_t id[10];
    int i,ret;
    pthread_attr_t attr[10];
    pthread_attr_init(&attr[0]);
    pthread_attr_init(&attr[1]);
    pthread_attr_init(&attr[2]);
    pthread_attr_setdetachstate(&attr[0],PTHREAD_CREATE_DETACHED);
    pthread_attr_setdetachstate(&attr[1],PTHREAD_CREATE_DETACHED);
  pthread_attr_setdetachstate(&attr[2],PTHREAD_CREATE_DETACHED);
  ret=pthread_create(&id[0],&attr[0],(void *) thread,NULL);
    ret=pthread_create(&id[1],&attr[1],(void*)thread,NULL);
    ret=pthread_create(&id[2],&attr[2],(void*)thread2,NULL);
// pthread_join(id[0],NULL);
//  pthread_join(id[1],NULL);
//    pthread_join(id[2],NULL);
    sleep(7);
    return (0);
}


开了两个thread,当thread中的加锁去掉之后,只会有一个输出,怎么理解?

[ 本帖最后由 cgp2001 于 2009-4-29 21:33 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2009-04-30 11:35 |只看该作者
假设两个thread一个为a,一个为b
当a得到mutex时,等待cond,得到cond,输出,释放mutx
b得到mutex,等待cond,这个时候你能保证b能得到cond吗?

论坛徽章:
0
3 [报告]
发表于 2009-04-30 11:39 |只看该作者
问题在于你的解除阻塞所有线程调用pthread_cond_broadcast,它只解除了两个thread中的一个。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP