Question

I'm required to do as the question title states. The restriction is that the consumer and producer have only 12 slots to put up to 20 chars into. I've got it working except that the last producer puts in only 13 chars (this is correct), and the last consumer does not recognize this. It writes 20 chars, which appends some extra chars to the end of my copied file. I have given it some thought and cannot find a suitable and efficient solution to have the consumer recognize that there are only 13 chars in the slot. I'm using the follow 2 lines to produce and consume (both use semaphores correctly and are running on separate threads simultaneously).

given by the problem at hand:

#define SLOTSIZE 20
#define SLOTCNT 12
char buffer[SLOTCNT][SLOTSIZE];

Producer:

count = fread(buffer[pIndex], sizeof(char), sizeof(buffer[pIndex]), myFile);

Consumer:

count = fwrite(buffer[cIndex], sizeof(char), sizeof(buffer[cIndex]), myFile);

This is a popular homework assignment so I'd prefer not to post much code. Any ideas? I believe I need an EOF marker at the end of those last 13 chars because I think that it is getting thrown out.

p.s. again for the producer, the result of the last read makes count = 13; and for the consumer, the last write makes count=20 and the extra chars ARE in the output file.

Was it helpful?

Solution

with only that amount of sample code, it's difficult to give a correct answer without some guesswork.

Your problem seems to be that you do not know the amount of valid bytes in your buffers in the writer. buffer seems to be an array of char arrays? If yes, you could make it an array of structs instead, for example:

struct buf
{
    int used_length;
    char b[20];
};
struct buf buffer[20];

Then do as follows:

producer:

buffer[pIndex].used_length = count = fread(buffer[pIndex].b, sizeof(char), sizeof(buffer[pIndex].b), myFile);

consumer:

count = fwrite(buffer[cIndex].b, sizeof(char), buffer[cIndex].used_length, myFile);

This way you will only write as much bytes as you read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top