环形缓冲池模拟

//cd 桌面
//g++ producerAndConsumer.c -o producerAndConsumer -lpthread
//./producerAndConsumer


#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <malloc.h>
#include <semaphore.h>
#include <unistd.h>
using namespace std;
#define SIZE 8
int buff[SIZE];
int *rear=buff;
int *front=buff;
pthread_mutex_t mutex[SIZE];//互斥信号量
sem_t signal_produce; //信号量
sem_t signal_consume;
int n,m;
void* produce(void *)
{
    while(1){
        sem_wait(&signal_produce);//非0的时候-1
        pthread_mutex_lock(&mutex[rear-buff]);
    int* Rear = rear; //如果不这样做可能会导致多个线程同时修改rear的值导致这个线程中后面使用的rear值都是错误的
    if(rear==buff+SIZE-1)//用数组来模拟环形队列
        rear=buff;
    else
            rear++;
        sleep(5);
    *Rear=1;
    printf("\n生产者装入 %d\n", Rear-buff);
    for(int i=0; i<SIZE; i++){//打印缓冲池
        printf("%d ", buff[i]);
    }
    printf("\n");
    pthread_mutex_unlock(&mutex[Rear-buff]);      
    sem_post(&signal_consume); //信号量+1
    int value_p=0;//打印信号量
    int value_c=0;
    sem_getvalue(&signal_produce, &value_p);
    printf("signal_produce:%d\n", value_p);
    sem_getvalue(&signal_consume, &value_c);
    printf("signal_consume:%d\n", value_c);
    }
}
void* consume(void *)
{
    while(1){
        sem_wait(&signal_consume);
        pthread_mutex_lock(&mutex[front-buff]);
    int* Front = front;
        if(front==buff+SIZE-1)
        front=buff;
    else
            front++;
        sleep(2);
    *Front=0;
    printf("\n消费者取走 %d\n", Front-buff);
    for(int i=0; i<SIZE; i++){
        printf("%d ", buff[i]);
    }
    printf("\n");
    pthread_mutex_unlock(&mutex[Front-buff]);
        sem_post(&signal_produce);
    int value_p=0;
    int value_c=0;
    sem_getvalue(&signal_produce, &value_p);
    printf("signal_produce:%d\n", value_p);
    sem_getvalue(&signal_consume, &value_c);
    printf("signal_consume:%d\n", value_c);
    }
}
int main(int argc, char const *argv[]) {
    printf("请输入生产者个数: ");
    scanf("%d",&n);
    printf("请输入消费者个数: ");
    scanf("%d",&m);
    pthread_t* thread_producer=(pthread_t*)malloc(sizeof(pthread_t)*n);
    pthread_t* thread_consumer=(pthread_t*)malloc(sizeof(pthread_t)*m);
    for(int i=0;i<SIZE;i++)
    pthread_mutex_init(&mutex[i],NULL);
    sem_init(&signal_produce,0,SIZE);//信号量初始化表示资源数目
    sem_init(&signal_consume,0,0);
    for(int i=0;i<SIZE;i++)
        buff[i]=0;
    for(int i=0;i<n;i++)
        pthread_create(&thread_producer[i],NULL,produce,NULL);
    for(int i=0;i<m;i++)
       pthread_create(&thread_consumer[i],NULL,consume,NULL);
    for(int i=0;i<n;i++)
        pthread_join(thread_producer[i],NULL);
    for(int i=0;i<m;i++)
        pthread_join(thread_consumer[i],NULL);
    free(thread_producer);
    free(thread_consumer);
    for(int i=0;i<SIZE;i++)
    pthread_mutex_destroy(&mutex[i]);
    sem_destroy(&signal_produce);
    sem_destroy(&signal_consume);
    return 0;
}

上一篇:Unity——技能系统(三)


下一篇:snprintf()函数使用方法