并发无锁之环形队列生产者消费者问题

一、生产者消费者问题
数组

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

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

       一种生产场所:缓冲区post

二、环形队列(缓冲区)spa

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

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

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

                    二、 添加一个计数器(信号量就是计数器因此这里用信号量完成计数器的功能)get

三、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

相关文章
相关标签/搜索