0

Classic producer consumer program. Currently trying to have the consumer wait if the queue is empty. The queue is a struct in memory. I'm having an issue with my pthread_cond_wait() function. We are not allowed global variables so I'm storing the pthread_cond's and mutex in memory in the queue struct. pthread_cond_wait() is returning the integer 6 into condWaitCheck, which indicates that either of the following is happening.

[EINVAL] The value specified by cond, mutex, or abstime is invalid.

[EINVAL] Different mutexes were supplied for concurrent pthread_cond_wait() or pthread_cond_timedwait() operations on the same condition variable.

[EINVAL] The mutex was not owned by the current thread at the time of the call.

And I can't seem to figure out which is my issue.

typedef struct queue {
    int element[MAX_QUEUE_SIZE];
    int prod_id[MAX_QUEUE_SIZE];
    int head;
    int tail;
    int remaining_elements; 
    pthread_mutex_t myMutex;
    pthread_cond_t condConsumer;
    pthread_cond_t condProducer;
} prod_cons_queue;

.

void queue_initialize( prod_cons_queue *q ){
    q->head = -1;
    q->tail = -1;
    q->remaining_elements=0;
    pthread_cond_init (q->condConsumer,NULL);
    pthread_cond_init (q->condProducer,NULL);
    pthread_mutex_init (q->myMutex,NULL);
}

.

void *consumerFunc(void* prodID) {
    int condWaitCheck;

    pthread_mutex_lock (&(((prod_cons_queue *)prodID)->myMutex));

    if (((prod_cons_queue *)prodID)->remaining_elements == 0){
        cout << "waiting in consumer..." << endl;
        pthread_cond_wait(&(((prod_cons_queue *)prodID)->condConsumer), &(((prod_cons_queue *)prodID)->myMutex));

        if (condWaitCheck!=0){
            cout << "There was an error on pthread_cond_wait:" << condWaitCheck << endl;
        }
    }
    cout << "unlocking from consumer... " << endl;
    pthread_mutex_unlock (&((prod_cons_queue *)prodID)->myMutex);

    return NULL;

 }

.

int main (){
    //Producer consumer queue initialized
    prod_cons_queue *q = (prod_cons_queue*) malloc (sizeof(prod_cons_queue*));
    //q->head = 42;

    //********************** CREATE CONSUMER **********************
    pthread_t consumer;
    int conCheck;
    conCheck =  pthread_create(&consumer,NULL,&consumerFunc,(void*)q); //passing void pointer type variable q

    if (conCheck!=0){
         cout << "Error:unable to create thread," << conCheck << endl;
         //exit(-1);
    }
john stamos
  • 1,054
  • 5
  • 17
  • 36

1 Answers1

0

The malloc function just allocates memory. It doesn't make that memory contain valid mutexes or condition variables. You need to initialize them. (Or, better yet, use new and modern C++ threading constructs.)

David Schwartz
  • 179,497
  • 17
  • 214
  • 278