用C语言实现--生产者与消费者的问题(PV操作)
来源:百度知道 编辑:UC知道 时间:2024/05/14 03:51:53
B:array [0..9] of products;
s1,s2: semaphore;
IN, out; integer;
IN:=0;out:=0;
cobegin
procedure producer;
c: products;
begin
L1:
produce (c);
p (s1);
B[IN]:=C;
IN:=(IN+1)mod 10;
v(s2);
goto L1
end;
procedure consumer;
x: products;
begin
L2:P(s2);
x:=B[out];
out:=(out+1) mod 10;
v(s1);
consume(x);
goto L2
end;
coend
其中的semaphore和products是预先定义的两个类型,在模拟实现中semaphore用integer或char等代替
要求可以运行出结果才给分,没结果那就算了!
这个问题蛮好的
我给你个程序
给我加分啊
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef HANDLE Semaphore; // 信号量的Windows原型
#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 /* 缓冲区个数 */
char *thing[10] = {"猪脸", "牛鞭", "羊腰", "驴蹄", "狼心", "狗肺", "猴肝", "老虎屁股", "大象肚", "河马大肠"};
struct Buffer
{
int product[BUFFER_NUM]; // 缓冲区
int start, end; // 两个指针
}