Chinaunix首页 | 论坛 | 博客
  • 博客访问: 417504
  • 博文数量: 121
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1393
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-11 12:17
个人简介

www.vibexie.com vibexie@qq.com

文章分类

全部博文(121)

文章存档

2015年(55)

2014年(66)

我的朋友

分类: C/C++

2014-10-15 13:06:17

代码下载a.zip

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<stdlib.h>
  4. #define MAX 1000

  5. pthread_mutex_t mutex;
  6. pthread_cond_t condc,condp;

  7. int bread_num=0;

  8. void *producer(void*argc)
  9. {
  10.     while(1)
  11.     {
  12.         pthread_mutex_lock(&mutex);

  13.         if(bread_num==MAX)
  14.         {
  15.             printf("Sum of bread is full ! call consumer...\n");
  16.             sleep(1);
  17.             pthread_cond_wait(&condp,&mutex);
  18.         }

  19.         bread_num++;
  20.         printf("Producer: Bread+1 now sum is %d\n",bread_num);
  21.         usleep(5000);
  22.         pthread_cond_signal(&condc);

  23.         pthread_mutex_unlock(&mutex);
  24.     }
  25.     pthread_exit(0);
  26. }

  27. void *consumer(void*argc)
  28. {
  29.     while(1)
  30.     {
  31.         pthread_mutex_lock(&mutex);

  32.         if(bread_num==0)
  33.         {
  34.             printf("Sum of bread is empty ! call produce...\n");
  35.             sleep(1);
  36.             pthread_cond_wait(&condc,&mutex);
  37.         }
  38.         bread_num--;
  39.         printf("Consumer: Bread-1 now sum is %d\n",bread_num);
  40.         usleep(5000);
  41.         pthread_cond_signal(&condp);

  42.         pthread_mutex_unlock(&mutex);
  43.     }
  44.     pthread_exit(0);

  45. }

  46. int main()
  47. {
  48.     pthread_t pro,con;

  49.     pthread_mutex_init(&mutex,NULL);
  50.     pthread_cond_init(&condp,NULL);
  51.     pthread_cond_init(&condc,NULL);
  52.     
  53.     pthread_create(&pro,NULL,producer,NULL);
  54.     pthread_create(&con,NULL,consumer,NULL);

  55.     pthread_join(pro,NULL);
  56.     pthread_join(con,NULL);

  57.     pthread_cond_destroy(&condp);
  58.     pthread_cond_destroy(&condc);
  59.     pthread_mutex_destroy(&mutex);

  60.     return 0;
  61. }
自己运行哦!
阅读(1244) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~