我当前的代码回答了生产者消费者的问题,但我想以不同的方式实现它。我不想使用全局变量来跟踪缓冲区堆栈中的计数。我的思维过程应该是什么?
typedef int semaphore;
semaphore mutex, full, empty;
int count = 0;
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
int buffer[N];
这些是使用count
的函数int remove_item()
{
int ret = buffer[--count];
buffer[count] = 0;
return ret;
}
void insert_item(int item)
{
buffer[count++] = item;
}
int produce_item(){
int item = rand()%50 +1;
printf("Producer produces %d\n",item);
sleep(1);
return item;
}
我的生产者消费者功能
void* consumer(void * arg) {
int item = 0;
while(1){
down(full);
down(mutex);
item = remove_item();
buffer[count++] = item;
up(mutex);
up(empty);
consume_item(item);
}
return 0;
}
void* producer(void* arg) {
int item, i =0;
while(1){
item = produce_item();
down(empty);
down(mutex);
insert_item(item);
up(mutex);
up(full);
sleep(1);
}