linux中的线程同步:生产者、消费者问题

linux中的线程同步:生产者、消费者问题
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_COUNT 5

int Buffer[BUFFER_COUNT]; //指针数组
int front = 0;
int tail = 0;

sem_t SemProd;
sem_t SemCon;

void* productor(void *arg)
{
    int counter = 0;
    while(1)
    {
        int ret = sem_wait(&SemProd);
        sleep(2); //模拟输入处理时延
        Buffer[tail] = counter;
        
        printf("in productor: %d, %d\n", counter++, ret);
        tail = (tail + 1) % BUFFER_COUNT; //
        sem_post(&SemCon);
    }
    return NULL;
}

void* consumer(void *arg)
{
    while(1)
    {
        sem_wait(&SemCon);
        sleep(1); //模拟输出处理时延
        printf("in consumer: %d, %d\n", Buffer[front], front);
        front = (front + 1) % BUFFER_COUNT;    
        sem_post(&SemProd);
    }
}

int main(int argv, char **argc)
{
    pthread_t id1, id2;
    sem_init(&SemProd, 0, BUFFER_COUNT);
    sem_init(&SemCon, 0, 0);

    pthread_create(&id1, NULL, productor, NULL);
    pthread_create(&id2, NULL, consumer, NULL);

    pthread_join(id1, NULL);
        pthread_join(id2, NULL);
}
linux中的线程同步:生产者、消费者问题

 

linux中的线程同步:生产者、消费者问题,布布扣,bubuko.com

linux中的线程同步:生产者、消费者问题

上一篇:SQL语句01


下一篇:C++单例模式