生产者-消费者”问题 用C语言编写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生产者-消费者”问题 用C语言编写相关的知识,希望对你有一定的参考价值。

参考技术A #include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#define P(S) WaitForSingleObject(S,INFINITE)//定义Windows下的P操作
#define V(S) ReleaseSemaphore(S,1,NULL)//定义Windows下的V操作
#define rate 1000
#define CONSUMER_NUM 10 /*消费者个数*/
#define PRODUCER_NUM 10 /*生产者个数*/
#define BUFFER_NUM 4 /*缓冲区个数*/
typedef HANDLE Semaphore; //信号量的Windows原型
char *thing[10]= "物品1","物品2","物品3","物品4","物品5",
"物品6","物品7","物品8","物品9","物品10";
struct Buffer

int product[BUFFER_NUM]; //缓冲区
int start,end; //两个指针
g_buf; Semaphore g_semBuffer,g_semProduct,g_mutex;
//消费者线程
DWORD WINAPI Consumer(LPVOID para)

int i=*(int *)para; //i表示第i个消费者
int ptr,j; //待消费的内容的指针
Sleep(100);
while(1)

P(g_semProduct); //有产品,先锁住缓冲区
P(g_mutex); //记录消费的物品
ptr=g_buf.start; //再移动缓冲区指针
g_buf.start=(g_buf.start+1)%BUFFER_NUM;
V(g_mutex); //让其他消费者或生产者使用 g_buf
printf("消费者%d:消费了buf[%d]里的=%s\n",i,ptr,thing[g_buf.product[ptr]]);
Sleep(rate*rand()%10+110);
//消费完毕,并释放一个缓冲
V(g_semBuffer);
if(j++>30)break;

getch();
return 0;

// 生产者线程
DWORD WINAPI Producer(LPVOID para)

int i=*(int *)para-CONSUMER_NUM;
int ptr,j;
int data; //产品
Sleep(100);
while(1)

Sleep(rate*rand()%10+110);
data=rand()%10;
//等待存放空间
P(g_semBuffer); //有地方,先锁住缓冲区
P(g_mutex);
// 记录消费的物品
ptr=g_buf.end;
// 再移动缓冲区指针
g_buf.end=(g_buf.end+1)%BUFFER_NUM;
//让其他消费者或生产者使用 g_buf
V(g_mutex);
printf("生产者%d:在buf[%d]里放入了%s\n",i,ptr,thing[data]);
g_buf.product[ptr]=data;
Sleep(rate/2*rand()%10+110);
//放好了完毕,释放一个产品
V(g_semProduct);

return 0;
int main(int argc,char *argv[])
//线程技术,前面为消费者线程,后面为生产者线程
HANDLE hThread[CONSUMER_NUM+PRODUCER_NUM]; //线程计数
//srand(time());
DWORD tid;
int i=0;
// 初始化信号量
g_mutex=CreateSemaphore(NULL,BUFFER_NUM,BUFFER_NUM,"mutexOfConsumerAndProducer");
g_semBuffer=CreateSemaphore(NULL,BUFFER_NUM,BUFFER_NUM,"BufferSemaphone");
g_semProduct=CreateSemaphore(NULL,0,BUFFER_NUM,"ProductSemaphone");
if(!g_semBuffer||!g_semProduct||!g_mutex)

printf("Create Semaphone Error!\n");
return -1;

int totalThreads=CONSUMER_NUM+PRODUCER_NUM;
// 开启消费者线程
for(i=0;i<CONSUMER_NUM;i++)

hThread[i]=CreateThread(NULL,0,Consumer,&i,0,&tid);
if(hThread[i])WaitForSingleObject(hThread[i],10);

//开启 生产者线程
for(;i<totalThreads;i++)

hThread[i]=CreateThread(NULL,0,Producer,&i,0,&tid);
if(hThread[i])WaitForSingleObject(hThread[i],10);

//生产者和消费者的执行
WaitForMultipleObjects(totalThreads,hThread,TRUE,INFINITE);
return 0;

以上是关于生产者-消费者”问题 用C语言编写的主要内容,如果未能解决你的问题,请参考以下文章

并行模式之生产者-消费者模式

JAVA模拟生产者与消费者实例

Linux生产者消费者模型

Linux生产者消费者模型

生产者消费者模型详解

生产者消费者模型详解