I am working on a consumer & producer multi-threaded program. The program has a shared variable num_elem
that is incremented in the producer and decremented in the consumer.
num elem
is providing information for a circular buffer that is using the struct queue
, such that queue
stores arrays of words being read from a file.
If the increment is changed from being inside of producer to being a function called by producer, then communication between the producer and consumer is fixed. Else, if the code to producer called as a function (as consumer is), then the used
boolean is changed to TRUE, when it is in fact not being used.
The code for each is below.
If the increment is called outside of producer, then the values to used
are changed to true. Why are they being changed when being called inside of producer, and not the when called as a function that is inside of producer?
CODE for producer
item_t *item = NULL;
for (i = 0; i < QUEUE_SIZE; i++) {
if (queue[(next_index + i) % QUEUE_SIZE].used == false) {
item = &queue[(next_index + i) % QUEUE_SIZE];
item->used = true;
num_elem++;
next_index = (i + 1) % QUEUE_SIZE;
}
}
CODE for consumer
item_t *consume_item() {
for (i = 0; i < QUEUE_SIZE; i++) {
if (queue[i].used == true) {
item_t *item = &queue[i];
item->used = false;
num_elem--;
return item;
}
}
return NULL;
Here is the github repo, if you would like to see the whole code
In the bad version, you need to add a break;
after line 150.