C-生产者消费者线程和静音



与生产者访问共享源时有关,我是否需要另一个条件变量/条件信号?因此,当共享资源锁定时,它确实会被阻止。我对消费者有一个条件变量,因此它可以等待,如果没有添加(消费)

,它不会尝试访问
int pnum;  // number updated when producer runs.
int csum;  // sum computed using pnum when consumer runs.
int (*pred)(int); // predicate indicating number to be consumed
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condc,condp;
int toConsume = 0; // condition varibale counter
int produceT() {
    //Start Critical Section
    pthread_mutex_lock(&mutex);
    scanf("%d",&pnum);
    toConsume++;
    //End Critical Section
    pthread_cond_signal (&condc);
    pthread_mutex_unlock(&mutex);
    return pnum;
}
void *Produce(void *a) {
  int p;
  p=1;
  while (p) {
    printf("producer thinking...n");
    sleep(1);
    printf("..done!n");
    p = produceT();
    printf("PRODUCED %dn",p);
  }
  printf("EXIT-Pn");
  pthread_exit(0);
}

int consumeT() {
    pthread_mutex_lock(&mutex); //protect buffer
    while(toConsume <=0){ // if nothing in buffer then wait
        pthread_cond_wait(&condc,&mutex);
    }
    pthread_mutex_unlock(&mutex); //release buffer
    //sleep()
    pthread_mutex_lock(&mutex); //protect buffer
    if ( pred(pnum) ) { csum += pnum; }
    toConsume--;
    pthread_mutex_unlock(&mutex);
    return pnum;
}
void *Consume(void *a) {
  int p;
  p=1;
  while (p) {
    printf("consumer thinking...n");
    sleep(rand()%3);
    printf("..done!n");
    p = consumeT();
    printf("CONSUMED %dn",csum);
  }
  printf("EXIT-Cn");
  pthread_exit(0);
}

int main (int argc, const char * argv[]) {
  // the current number predicate
  static pthread_t prod,cons;
    long rc;
  pred = &cond1;
  if (argc>1) {
    if      (!strncmp(argv[1],"2",10)) { pred = &cond2; }
    else if (!strncmp(argv[1],"3",10)) { pred = &cond3; }
  }
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&condc,NULL);//Initialize consumer condition variable
  pthread_cond_init(&condp,NULL);//Initialize producer condition variable
  pnum = 999;
  csum=0;
  srand(time(0));
  printf("Creating Producer:n");
    rc = pthread_create(&prod,NULL,Produce,(void *)0);
    if (rc) {
            printf("ERROR return code from pthread_create(prod): %ldn",rc);
            exit(-1);
        }
  printf("Creating Consumer:n");
    rc = pthread_create(&cons,NULL,Consume,(void *)0);
    if (rc) {
            printf("ERROR return code from pthread_create(cons): %ldn",rc);
            exit(-1);
        }
    pthread_join( prod, NULL);
    pthread_join( cons, NULL);

  printf("csum=%d.n",csum);
  return 0;
}

条件变量是一种有效阻塞线程直到验证某个条件的方法。

您在消费者中使用条件变量仅仅是因为您指示不能消耗是否没有任何东西可以消耗 - 因此您决定阻止,直到有东西要消耗为止。在您的情况下,这发生在toConsume == 0

时发生

您可能会规定生产者还必须等待 - 这完全取决于您的规格。一些想法:

  • 您可能需要防止变量越过某个值(例如1000INT_MAX以避免溢出)。
  • 如果您使用圆形缓冲区将您的物质放置在内缓冲区。这是教科书中教授生产者消费者的最常见方法:)

最新更新