Вопрос о потребительской и производственной ветке

У меня проблема с циклами сна в файле ProducerConsumer.h. Если я закомментирую sleep(rnum), программа получит доступ к строке printf("продюсер произведен%d\n", item); Если это не закомментировано, оно никогда не получит доступ к этой строке, и я не могу понять, почему. Вот мой код в 3 отдельных файлах, я был бы признателен за любую помощь, спасибо.

buffer.h:

typedef int buffer_item;
#define BUFFER_SIZE 5


int insert_item(buffer_item item);
int remove_item(buffer_item *item);

ProducerConsumer.h:

#include <stdlib.h> /* required for rand() */
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include "buffer.h"
#define RAND_DIVISOR 100000000;
#define TRUE 1

int counter;
buffer_item buffer[BUFFER_SIZE];
pthread_mutex_t mutex;
sem_t full, empty;

/* Producer Thread */
void *producer(void *param) {
    buffer_item item;

    while(TRUE) {
      /* sleep for a random period of time */
      int rNum = rand() / RAND_DIVISOR;
      sleep(rNum);
      printf("producer produced %d\n", item);

      /* generate a random number */
      item = rand();

      /* acquire the empty lock */
      sem_wait(&empty);

      /* acquire the mutex lock */
      pthread_mutex_lock(&mutex);

      if(insert_item(item)) {
         fprintf(stderr, " Producer report error condition\n");
      } else {
         printf("producer produced %d\n", item);
      }

      /* release the mutex lock */
      pthread_mutex_unlock(&mutex);

      /* signal full */
      sem_post(&full);
    }

}

/* Consumer Thread */
void *consumer(void *param) {
    buffer_item item;

    while(TRUE) {
      /* sleep for a random period of time */

      int rNum = rand() / RAND_DIVISOR;
       sleep(rNum);
      /* aquire the full lock */

      sem_wait(&full);
      /* aquire the mutex lock */

      pthread_mutex_lock(&mutex);
      if(remove_item(&item)) {
         fprintf(stderr, "Consumer report error condition\n");
      } else {
         printf("consumer consumed %d\n", item);`enter code here`
      }

      /* release the mutex lock */
      pthread_mutex_unlock(&mutex);

      /* signal empty */
      sem_post(&empty);
    }
}

int insert_item(buffer_item item) {
    if(counter < BUFFER_SIZE) {
      buffer[counter] = item;
      counter++;
      return 0;
    } else {
      return -1;
    }
}

int remove_item(buffer_item *item) {
    if(counter > 0) {
      *item = buffer[(counter-1)];
      counter--;
      return 0;
     } else {
      return -1;
     }
}

main.cpp:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include "ProducerConsumer.h"
#include "buffer.h"

pthread_t tid;
pthread_attr_t attr;

void initializeData()
{
    pthread_mutex_init(&mutex, NULL);
    sem_init(&full, 0, 0);
    sem_init(&empty, 0, BUFFER_SIZE);
    pthread_attr_init(&attr);
    counter = 0;
}

int main() {
   int i;
   int numProd = 5; /* Number of producer threads */
   int numCons = 5; /* Number of consumer threads */

   initializeData();

   /* Create the producer threads */
   for(i = 0; i < numProd; i++) {
      /* Create the thread */
      pthread_create(&tid,&attr,producer,NULL);
    }

   /* Create the consumer threads */
   for(i = 0; i < numCons; i++) {
      /* Create the thread */
      pthread_create(&tid,&attr,consumer,NULL);
   }

   void *producer(void *param);
   void *consumer(void *param);

   /* Exit the program */
   printf("Exit the program\n");

   exit(0);
}

1 ответ

Значение RAND_MAX скорее всего, по крайней мере, 32767, вызывая следующую строку:

int rNum = rand() / RAND_DIVISOR;// defined as 100000000

для большинства всегда установлены rNum == 0.

Измените оператор, чтобы получить ненулевое значение:

int rNum = 1 + rand() % 10;// yields 1-10 

Кроме того, вызовите srand() один раз и перед использованием rand(), например:

void *producer(void *param) {
    buffer_item item;

    srand((unsigned) time(&t));
    ...
Другие вопросы по тегам