CaptRage61
Programmer
I am working on using semaphores to keep two threads from writing to the same variable but this is now working correctly, I beleive that the semaphore is created correctly can anyone tell if this is right:
Code:
int p(){
//sem is the sembuf struct
//x is the semid
sem.sem_op = -1;
semop(x, &sem, 1);
}
int v(){
sem.sem_op = 1;
semop(x, &sem, 1);
}
int producer()
{
int i,in, local, sum = 0;
printf(" Producer: writing %d items.\n", PRODUCER_REPS);
i = 0;
while (i < PRODUCER_REPS)
{
while (counter == BUFFER_SIZE) ;
buffer[in] = ++i;
in = (in + 1) % BUFFER_SIZE;
// The next 4 lines implement a "slow" counter++;
local = counter;
local++;
if (i == 10) work(100000);
counter = local;
p(); //this will force the consumer to wait till this
//command is executed before it can update counter
//and the buffer
sum += i;
}
printf(" Producer done! Checksum was %d\n", sum);
}
int consumer()
{
int i;
int out;
int sum = 0;
printf(" Consumer: reading items.\n");
i = 0;
out = 0;
while (i < PRODUCER_REPS)
{
while (counter == 0) ;
v(); //waits for producer to update counter before
//it can update counter and buffer
i = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
sum += i;
}
printf(" Consumer checksum = %d\n",sum);
}