0
void producer(char* line){
    
    /* Produtor */

    pthread_mutex_lock(&buffer_mutex);
    while (occupied >= MAX_COMMANDS){
        printf("produzi wait\n");
        pthread_cond_wait(&less, &buffer_mutex);
    }
    
    printf("insere no index: %d\n",buff_write_idx);
    insertCommand(line, buff_write_idx);
    buff_write_idx = (buff_write_idx + 1) % MAX_COMMANDS;
    occupied++;
    printf("produzi. occupied = %d\n", occupied);
    pthread_cond_signal(&more);
    pthread_mutex_unlock(&buffer_mutex);
}

/******************************************************/

char* consumer(){

    pthread_mutex_lock(&buffer_mutex);
    while(occupied <= 0 ){

        printf("consumidor wait\n");
        pthread_cond_wait(&more, &buffer_mutex);

    }

    printf("retira do index: %d\n",buff_read_idx);
    char* command = removeCommand(buff_read_idx);
    buff_read_idx = (buff_read_idx + 1) % MAX_COMMANDS;
    occupied--;
    printf("consumidor. occupied = %d\n", occupied);

    pthread_cond_signal(&less);      
    pthread_mutex_unlock(&buffer_mutex);

    return command;
}

My problem is that after I run my program in the end, after the buffer done the operations necessary, in the CONSUMER(consumer while waiting for signal of producer) is always waiting for a producer but the producer is already empty. Suggestions to exit the loop?

  • 1
    Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Then please [edit] your question to include a [mcve], including how you use these functions. – Some programmer dude Nov 18 '20 at 10:55
  • It is difficult to understand what you mean with " the producer is always waiting for a producer but the producer is already empty". – Rachid K. Nov 18 '20 at 11:44
  • Error. What i wanted to say is the waiting of the consumer is always waiting for a producer but the producer will not send more signal because the buffer will not receive more arguments and is already empty. – Goncalo Castilho Nov 18 '20 at 12:02
  • So you mean that at one moment the producer has nothing to produce and stop ? So, you must create a sort of "End Of File" event for the consumer. For example, when the producer is finished, it can set occupied to -1 and the consumer must check that : if occupied is 0, it calls pthread_cond_wait(); if occupied is > 0, it consumes the data. If occupied is < 0, it "exits". – Rachid K. Nov 18 '20 at 12:16
  • But if i am using threads and for example i have 4 threads. If one of the threads end, the occupied will become -1 but the buffer it isnt empty yet. – Goncalo Castilho Nov 18 '20 at 13:03
  • done thanks. sorry for the incovenient. – Goncalo Castilho Nov 18 '20 at 13:15

0 Answers0