I am having issues getting my project to work and was hoping someone could assist. The guidelines are as follows:
You will use the pthread package to create 4 producer threads and 4 consumer threads. Each producer thread inserts character ‘X’ into a buffer of size 10,000,000 characters. Each consumer thread removes the most recently-inserted character from the buffer. Each thread then repeats the process
So far my code looks like this:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <pthread.h>
#define N 10000000
sem_t mutex;
sem_t full;
sem_t empty;
typedef struct
{
char const* buf[N];
char in;
char out;
} bufferItems;
bufferItems sharedBuffer;
void *producer(void *arg) {
while(1) {
sem_wait(&empty);
sem_wait(&mutex);
sharedBuffer.buf[sharedBuffer.in] = "X";
sharedBuffer.in = (sharedBuffer.in+1)%N;
printf("Producer\n");
sem_post(&mutex);
sem_post(&full);
}
}
void *consumer(void *arg){
while(1){
sem_wait(&full);
sem_wait(&mutex);
sharedBuffer.buf[sharedBuffer.out] = NULL;
sharedBuffer.out = (sharedBuffer.out+1)%N;
printf("Consumer\n");
sem_post(&mutex);
sem_post(&empty);
}
}
int main(void) {
sem_init(&mutex, 0, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, N);
pthread_t p;
pthread_t c;
// create four producer threads
for(int t=0; t<4; t++){
printf("In main: creating producer thread %d\n", t);
int err = pthread_create(&p,NULL,producer,NULL);
if (err){
printf("ERROR from pthread_create() on producer thread %d\n", err);
exit(-1);
}
}
// create four consumer threads
for(int t=0; t<4; t++){
printf("In main: creating consumer thread %d\n", t);
int err = pthread_create(&c,NULL,consumer,NULL);
if (err){
printf("ERROR; from pthread_create() on consumer thread %d\n", err);
exit(-1);
}
}
}
But the output I get when I run it is this:
In main: creating producer thread 0
In main: creating producer thread 1
In main: creating producer thread 2
In main: creating producer thread 3
In main: creating consumer thread 0
In main: creating consumer thread 1
In main: creating consumer thread 2
In main: creating consumer thread 3
It seems as though the child threads are either not executing, or the semaphores are not working properly so there is deadlock. Any recommendation on how to make my code better or work properly would be greatly appreciated.