producers-consumers/src/consumer.c

62 lines
1.5 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);
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-12 22:59:06 -05:00
// Consumer main function
// TODO: Add waiting for one consumer at a time
// Add ability to use shared memory
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
}
}
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-12 22:59:06 -05:00
// Manage item taken from 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-12 22:59:06 -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
}