1、生产者消费者问题

       三种关系:生产者--生产者(互斥);消费者-消费者(互斥);生产者--消费者(互斥同步)

       两个角色:生产者;消费者

       一种生产场所:缓冲区

2、环形队列(缓冲区)

  数据结构:可以有多种,这里选用数组,逻辑上将a[0]和a[size-1]相连构成环形队列

  判断空/判断满:当读指针和写指针指向同一个区域为空,或者满(但不能区分空或者满)

  两种方案:1、即尾结点与首结点之间至少留有一个元素的空间。                   

                    2、 添加一个计数器(信号量就是计数器所以这里用信号量完成计数器的功能)

3、semaphore

        信号量就是一种计数器,其最重要的操作就是P,V操作;

        P操作惊醒count--;V操作进行cont++;

        P,V操作本身是原子操作!!!(即保证了互斥)

代码:单生产者-单消费者

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int round[64];
sem_t space_nums;
sem_t data_nums;
void *consumer(void *arg)
{
  int index=0;
  while(1)
  {
    sem_wait(&data_nums);
    int num=round[index];
    printf("%d consumer is done...%d\n",index,num);
    sem_post(&space_nums);
    index++;
    index%=64;
    sleep(1);
  }
}
void *producter(void *arg)
{
  int index=0;
  while(1)
  {
    //space_nums--;
    sem_wait(&space_nums);
    int num=rand()%123;
    round[index]=num;
    printf("%d producter is done...%d\n",index,num);
    sem_post(&data_nums);
    index++;
    index%=64;
    sleep(1);
  }
}
int main()
{
  pthread_t id1,id2;
  sem_init(&space_nums,0,64);
  sem_init(&data_nums,0,0);
  pthread_create(&id1,NULL,consumer,NULL);
  pthread_create(&id2,NULL,producter,NULL);
  pthread_join(id1,NULL);
  pthread_join(id2,NULL);
  sem_destroy(&space_nums);
  sem_destroy(&data_nums);
}

wKiom1ePMrfinRS8AABK_uxKXqU489.png

代码:多生产者-多消费者 //本身已经实现了P,V的原子操作已经实现了互斥

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int round[64];
sem_t space_nums;
sem_t data_nums;
void *consumer(void *arg)
{
  int index=0;
  while(1)
  {
    sem_wait(&data_nums);
    int num=round[index];
    printf("%d consumer%d is done...%d\n",index,arg,num);
    sem_post(&space_nums);
    index++;
    index%=64;
    sleep(1);
  }
}
void *producter(void *arg)
{
  int index=0;
  while(1)
  {
    //space_nums--;
    sem_wait(&space_nums);
    int num=rand()%123;
    round[index]=num;
    printf("%d producter%d is done...%d\n",index,arg,num);
    sem_post(&data_nums);
    index++;
    index%=64;
    sleep(1);
  }
}
int main()
{
  pthread_t id1,id2,id3,id4;
  sem_init(&space_nums,0,64);
  sem_init(&data_nums,0,0);
  pthread_create(&id1,NULL,consumer,(void *)1);
  pthread_create(&id3,NULL,consumer,(void *)2);
  pthread_create(&id2,NULL,producter,(void *)1);
  pthread_create(&id4,NULL,producter,(void *)2);
  pthread_join(id1,NULL);
  pthread_join(id3,NULL);
  pthread_join(id4,NULL);
  pthread_join(id2,NULL);
  sem_destroy(&space_nums);
  sem_destroy(&data_nums);
}

wKioL1ePMf_DdVABAADNXAL1X4M964.png