首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生产者消费者synchronizing11

生产者消费者synchronizing11
EN

Stack Overflow用户
提问于 2014-07-26 20:39:06
回答 1查看 164关注 0票数 0
代码语言:javascript
复制
#include <stdio.h>
#include <pthread.h>
#define MAX 10                                  /* maximum iterations */
int number;                                     /* the resource */
pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER;  /* to protect the resource*/
/*
    Condition variable to signal consumer that a new number is available for
    consumption.
*/
pthread_cond_t sig_consumer= PTHREAD_COND_INITIALIZER;
/*
      Condition variable to signal the producer that
      (a) the new number has been consumed,
      (b) generate another one.
*/
pthread_cond_t sig_producer= PTHREAD_COND_INITIALIZER;
void *consumer(void *dummy)
{
      int printed= 0;
      printf("Consumer : \"Hello I am consumer #%ld. Ready to consume numbers"
             " now\"\n", pthread_self());

      while (1)
      {
         pthread_mutex_lock(&mu);
         /* Signal the producer that the consumer is ready. */
         pthread_cond_signal(&sig_producer);
         /* Wait for a new number. */
         pthread_cond_wait(&sig_consumer, &mu);
         /* Consume (print) the number. */
         printf("Consumer : %d\n", number);
         /* Unlock the mutex. */
         pthread_mutex_unlock(&mu);

         /*
           If the MAX number was the last consumed number, the consumer should
           stop.
         */
         if (number == MAX)
         {
           printf("Consumer done.. !!\n");
           break;
         }
      }
}
        /**
          @func producer
          This function is responsible for incrementing the number and signalling the
          consumer.
        */
void *producer(void *dummy)
{
      printf("Producer : \"Hello I am producer #%ld. Ready to produce numbers"
             " now\"\n", pthread_self());
      while (1)
      {
            pthread_mutex_lock(&mu);
            number ++;
            printf("Producer : %d\n", number);
            /*
              Signal the consumer that a new number has been generated for its
              consumption.
            */
            pthread_cond_signal(&sig_consumer);
            /*
              Now wait for consumer to confirm. Note, expect no confirmation for
              consumption of MAX from consumer.
            */
            if (number != MAX)
              pthread_cond_wait(&sig_producer, &mu);

            /* Unlock the mutex. */
            pthread_mutex_unlock(&mu);

            /* Stop if MAX has been produced. */
            if (number == MAX)
            {
              printf("Producer done.. !!\n");
              break;
            }
      }
}

void main()
{
      int rc, i;
      pthread_t t[2];
      number= 0;
      /* Create consumer & producer threads. */
      if ((rc= pthread_create(&t[0], NULL, consumer, NULL)))
        printf("Error creating the consumer thread..\n");
      if ((rc= pthread_create(&t[1], NULL, producer, NULL)))
        printf("Error creating the producer thread..\n");

      /* Wait for consumer/producer to exit. */
      for (i= 0; i < 2; i ++)
        pthread_join(t[i], NULL);

      printf("Done..\n");
} 

问:如果消费者线程在生产者线程之前启动,那么程序会提供预期的结果,但如果生产者线程先启动,那么消费者将从2号开始消费;消费者无法消费1号。即使生产者线程先启动,如何在不引入任何额外变量或睡眠的情况下纠正程序?

EN

回答 1

Stack Overflow用户

发布于 2014-07-27 06:06:33

pthread_cond_t的问题在于它的名称。尽管名义上是一种“状态”,但它具有no state...特别是,它根本不记得它已经发出过信号--如果您认为它可能会计算它已经发出过多少次信号,那么您会感到失望(因为您需要一个信号量)。换句话说,如果在发送信号时没有pthread在等待某个条件,那么该信号将不起作用并被遗忘。

“条件”更好地被认为是“等待队列”,其中pthread等待某些状态被更新。所以通常你有一些状态,由互斥锁保护。如果该状态不是pthread继续运行所需的状态,则pthread等待“条件”。当状态被更新时,可以用信号通知“条件”。当服务员醒来时,它必须检查状态,并决定现在是否一切都准备好了。

在有两个或更多pthread等待的情况下,标准允许pthread_cond_signal()唤醒一个、两个或多个或所有的服务员。互斥确保服务生对状态的访问是串行化的,但是服务生不能(通常,出于这个原因)假定状态在信号之后是不变的。所以,给服务员写信是很常见的:

代码语言:javascript
复制
pthread_mutex_lock(&mutex) ;
....
while(...what we need to continue...)
  pthread_cond_wait(&cond, &mutex) ;
....
pthread_mutex_unlock(&mutex) ;

这反映了国家的重要性,以及“条件”的贡献有多小。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24971109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档