producers-consumers/src/producer.c

83 lines
2.0 KiB
C
Raw Normal View History

2022-10-11 20:18:38 -05:00
#include <stdlib.h>
2022-10-12 21:11:15 -05:00
#include <stdio.h>
#include <sys/shm.h>
#include <time.h>
#include <unistd.h>
2022-10-12 15:44:12 -05:00
#include "shared.h"
2022-10-11 19:53:52 -05:00
int GetNextFreeSlot(SharedStruct* sharedMem);
void Producer(SharedStruct* sharedMem);
int produce_item(void);
int insert_item(int item, SharedStruct* sharedMem);
int main(int argc, char* argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s SharedID# \n", argv[0]);
exit(1);
}
srandom((unsigned int) time(NULL));
int sharedID = StringToNumber(argv[1]);
SharedStruct* sharedMem = shmat(sharedID, NULL, 0);
Producer(sharedMem);
sem_post(&sharedMem->semConsumer);
return 0;
}
int GetNextFreeSlot(SharedStruct* sharedMem)
{
int slot = -1;
for (int i = 0; i < 10; i++)
{
if ((sharedMem->buffer[i] != -1) && (sharedMem->buffer[(i+1)%10] == -1))
{
slot = (i+1)%10;
return slot;
}
}
return slot;
}
2022-10-12 22:59:06 -05:00
// Producer main function
// TODO: Add waiting for one producer at a time
// Add ability to use shared memory
void Producer(SharedStruct* sharedMem)
2022-10-11 20:18:38 -05:00
{
int insertNum;
// TODO: For testing purposes, revert max to 100
for (int i = 0; i < 5; i++)
2022-10-11 20:18:38 -05:00
{
2022-10-12 21:11:15 -05:00
insertNum = produce_item();
printf("%d is inserted.\n", insertNum);
2022-10-12 15:44:12 -05:00
// sem_wait(&semProducer);
// down(&empty);
// down(&mutex);
// if (insert_item(insertNum, sharedMem) == 0)
insert_item(insertNum, sharedMem);
// {
// --i;
// continue;
// }
2022-10-12 15:44:12 -05:00
// up(&mutex);
// up(&full);
break;
2022-10-11 20:18:38 -05:00
}
}
2022-10-12 22:59:06 -05:00
// Generate a number between 0 and 9
int produce_item(void)
2022-10-11 20:18:38 -05:00
{
2022-10-12 22:59:06 -05:00
return random() % 10;
2022-10-11 20:18:38 -05:00
}
2022-10-12 22:59:06 -05:00
// Insert a number into the shared memory
int insert_item(int item, SharedStruct* sharedMem)
2022-10-11 19:50:07 -05:00
{
int slot = GetNextFreeSlot(sharedMem);
if (slot == -1)
return 0;
sharedMem->buffer[0] = item;
return 1;
2022-10-11 19:50:07 -05:00
}