Chinaunix首页 | 论坛 | 博客
  • 博客访问: 557498
  • 博文数量: 142
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1452
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-12 16:28
文章分类

全部博文(142)

文章存档

2016年(10)

2015年(60)

2014年(72)

我的朋友

分类: C/C++

2014-12-15 11:13:36

生产者与消费者模型:


点击(此处)折叠或打开

  1. #include "unipc.h"

  2. #define MAXNITIEMS 1000000
  3. #define MAXNTHREADS 100

  4. int nitems;

  5. /*critical region*/
  6. struct {
  7.     pthread_mutex_t mutex; /*mutex*/
  8.     int buff[MAXNITIEMS]; /*shared data array*/
  9.     int nput;
  10.     int nval;
  11. } shared = {
  12.     PTHREAD_MUTEX_INITIALIZER,{0},0,0
  13. };


  14. int
  15. set_concurrency(int level)
  16. {
  17. #ifdef HAVE_THR_SETCONCURRENCY_PROTO
  18.     int thr_setconcurrency(int);

  19.     return(thr_setconcurrency(level));
  20. #else
  21.     return(0);
  22. #endif
  23. }

  24. void
  25. Set_concurrency(int level)
  26. {
  27.     if (set_concurrency(level) != 0){
  28.         printf("set_concurrency error\n");
  29.     }
  30. }

  31. void *produce(void *),*consume(void*);



  32. void *produce(void *arg)
  33. {
  34.     for(;;) {
  35.         pthread_mutex_lock(&shared.mutex);
  36.         if(shared.nput >= nitems) {
  37.             pthread_mutex_unlock(&shared.mutex);
  38.             return NULL;
  39.         }
  40.         shared.buff[shared.nput++] = shared.nval++;
  41.         pthread_mutex_unlock(&shared.mutex);
  42.         (*(int*)arg)++;
  43.     }
  44.     return NULL;
  45. }

  46. void *consume(void *arg)
  47. {
  48.     int i;
  49.     for(i = 0;i < nitems;i++) {
  50.         if(i != shared.buff[i]) {
  51.             printf("i = %d,buffer[i] = %d\n",i,shared.buff[i]);
  52.         }
  53.     }
  54.     return NULL;
  55. }
  56. int min(int a, int b)
  57. {
  58.     if(a < b) {
  59.         return a;
  60.     }else {
  61.         return b;
  62.     }
  63. }
  64. int main(int argc, char *argv[])
  65. {
  66.     int i, nthreads,count[MAXNTHREADS];
  67.     pthread_t tid_produce[MAXNTHREADS],tid_consume;


  68.     if(argc != 3) {
  69.         printf("usage: produces2 <#item> <#threads>\n");
  70.         return -1;
  71.     }

  72.     nitems = min(atoi(argv[1]),MAXNITIEMS);
  73.     nthreads = min(atoi(argv[2]),MAXNTHREADS);

  74.     Set_concurrency(nthreads);

  75.     for(i = 0; i < nthreads; i++)
  76.     {
  77.         count[i] = 0;
  78.         pthread_create(&tid_produce[i],NULL,produce,&count[i]);
  79.     }

  80.     for(i = 0; i < nthreads; i++) {
  81.         pthread_join(tid_produce[i],NULL);
  82.         printf("thread %zu, count=%d\n",tid_produce[i],count[i]);
  83.     }

  84.     pthread_create(&tid_consume,NULL,consume,NULL);

  85.     pthread_join(tid_consume,NULL);

  86.     exit(0);
  87. }

阅读(416) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~