producers-consumers/src/consumer.c

62 lines
1.6 KiB
C
Raw Normal View History

#include <stdlib.h>
#include <stdio.h>
#include <sys/shm.h>
#include <unistd.h>
2022-10-12 15:44:12 -05:00
#include "shared.h"
2022-10-11 19:53:52 -05:00
void StartConsumer(SharedStruct* sharedMem);
void Consume(SharedStruct* sharedMem);
2022-10-15 16:06:55 -05:00
void consume_item(int item, SharedStruct* sharedMem);
int remove_item(SharedStruct* sharedMem);
2022-10-15 20:29:52 -05:00
// Checks for SharedID, then begins producing numbers into shared memory.
int main(int argc, char* argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s SharedID# \n", argv[0]);
exit(1);
}
int sharedID = StringToNumber(argv[1]);
SharedStruct* sharedMem = shmat(sharedID, NULL, 0);
StartConsumer(sharedMem);
return 0;
}
2022-10-15 20:29:52 -05:00
// Starts the consumer process.
void StartConsumer(SharedStruct* sharedMem)
2022-10-11 20:18:38 -05:00
{
for (int i = 0; i < 5; i++)
2022-10-11 20:18:38 -05:00
{
sem_wait(&sharedMem->full);
Consume(sharedMem);
sem_post(&sharedMem->empty);
2022-10-11 20:18:38 -05:00
}
}
2022-10-15 20:29:52 -05:00
// Takes a number from the shared memory and consumes it.
void Consume(SharedStruct* sharedMem)
{
int consumeNum;
sem_wait(&sharedMem->mutex);
consumeNum = remove_item(sharedMem);
consume_item(consumeNum, sharedMem);
printf("%d was consumed.\n", consumeNum);
sem_post(&sharedMem->mutex);
return;
}
2022-10-15 20:29:52 -05:00
// Increments the count of numbers generated so far in shared memory.
2022-10-15 16:06:55 -05:00
void consume_item(int item, SharedStruct* sharedMem)
2022-10-11 20:18:38 -05:00
{
2022-10-15 16:06:55 -05:00
sharedMem->count[item]++;
return;
2022-10-11 20:18:38 -05:00
}
2022-10-15 20:29:52 -05:00
// Take item out of shared memory.
2022-10-15 16:06:55 -05:00
int remove_item(SharedStruct* sharedMem)
2022-10-11 19:50:07 -05:00
{
2022-10-15 16:06:55 -05:00
int item = sharedMem->buffer[0];
sharedMem->buffer[0] = -1;
return item;
2022-10-11 19:50:07 -05:00
}