I have created the following code to act as a buffer between two threads. I am trying to add support to handle empty and or full buffers, and am not sure how to address this. Would it be done through condition variables? Thanks.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h> //for sleep() if needed
const int N = 100000000; // buffer size
int Buffer[N];
int NumOccupied = 0; // Number of items currently in Buffer
int FirstOccupied = 0; // Index to first (next) item in Buffer to add/remove
pthread_mutex_t BuffMutt = PTHREAD_MUTEX_INITIALIZER;
// Constraint: To start, will assume that N values will be added or read!!
void buffadd(int value)
{
pthread_mutex_lock(&BuffMutt);
Buffer[FirstOccupied + NumOccupied] = value;
//pthread_yield();
//sleep(1);
++NumOccupied;
pthread_mutex_unlock(&BuffMutt);
}
int buffrem()
{
int value;
pthread_mutex_lock(&BuffMutt);
value = Buffer[FirstOccupied];
++FirstOccupied;
--NumOccupied;
pthread_mutex_unlock(&BuffMutt);
return(value);
}
void *tcode1(void *empty)
{
//Simply adds ten values to the buffer
int i;
for(i = 0; i<N;i++)
buffadd(i);
}
void *tcode2(void *empty)
{
//Reads values off buffer and confirms the values
int i, val;
for(i = 0; i<N; i++)
{
val = buffrem();
if(val != i)
{
printf("removed %d, expected %d\n", val, i);
}
}
}
main()
{
pthread_t t1, t2;
pthread_create(&t1, NULL, tcode1, NULL);
pthread_create(&t2, NULL, tcode2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}