码迷,mamicode.com
首页 > 编程语言 > 详细

生产者消费者问题(基于线程和无名信号量)

时间:2014-11-14 19:30:36      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   os   sp   for   

//5.生产者消费者问题
#include <pthread.h>  
#include <semaphore.h>  
#include <unistd.h>  
#include <stdio.h>  
#define MAX 50  
#define BUFSIZE 10  //仓库的大小
int buf[BUFSIZE]={0};  
int in=0;  
int out=0;  
sem_t full,empty;   
void* producer(void* arg)  
{  
   int i;  
   for (i = 1;i<=MAX;++i)  
    {  
       /*produce*/  
       sem_wait(&full);  
       buf[in++]=i;  
       in%=BUFSIZE;  
       printf("生产了第%d个产品\n" ,i);
       sem_post(&empty);  
    }  
   pthread_exit((void*)"thread1 exit\n");  
}  
void* comsumer(void* arg)  
{  
   int i,data_c;  
   for (i = 1;i<= MAX; ++i)  
    {  
       /*comsumer*/  
       sem_wait(&empty);  
       data_c=buf[out++]; 
       out%=BUFSIZE;
       printf("消费了%d个产品\n" ,data_c);
       sem_post(&full);  
    }  
   pthread_exit((void*)"thread2 exit\n");  
}  
int main(void)  
{  
   void *tret;  
   sem_init(&full,0,10);  //信号量的初始值为10和仓库的大小保持一致
   sem_init(&empty,0,0);  
   pthread_t tid_producer,tid_comsumer;  
   pthread_create(&tid_producer,NULL,producer,NULL);  
   pthread_create(&tid_comsumer,NULL,comsumer,NULL);  
   pthread_join(tid_producer,&tret);  
   printf("%s\n",(char*)tret);  
   pthread_join(tid_comsumer,&tret);  
   printf("%s\n",(char*)tret);  
   sem_destroy(&full);  
   sem_destroy(&empty);  
   return 0;
}
此程序一定要注意信号量的个数一定要和仓库的存储空间大小数值上要一样大,此程序两个数都为10

 

生产者消费者问题(基于线程和无名信号量)

标签:des   style   blog   io   color   ar   os   sp   for   

原文地址:http://www.cnblogs.com/leijiangtao/p/4097948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!