生产者和消费者问题

这是一道学习linux时候的历史遗留问题。。。

题目:用线程实现:生产者与消费者:
一个缓冲区,两个线程:生产者和消费者,一个放入缓存一个从缓存取数据,生产者在满时等待,消费者在空时等待,两者互斥执行。

实现:用一个有名管道myfifo作为缓存,因为两者互斥执行,所以myfifo属于临界资源。
而对临界资源的互斥与同步要用信号量来解决。
使用3个信号量,一个二值信号量(mutex )控制是否允许对管道操作。
一个avail 表示缓冲区中的空单元数 初始值为N
一个full信号量表示缓冲区中的非空单元数 初始值为 0
这里写图片描述

代码实现:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <string.h>
#define  FIFO "myfifo"
#define BUFFER_SIZE 5
#define TIME_SIZE 30

int fd;
time_t end_time;
sem_t mutex, full, avail;
char buf_r[100];

void *producer(void *arg)
{
    int i, nwrite;

    while(time(NULL) < end_time)
    {
        sem_wait(&avail);
        sem_wait(&mutex);

        if((nwrite = write(fd, "hello", 5)) == -1)
        {
            if(errno == EAGAIN){
                printf("The FIFO has not been read yet. Please try later\n");   
            }
        }
        else
        {
            printf("write hello to the FIFO\n");
        }

        sem_post(&full);
        sem_post(&mutex);
        sleep(1);

     } 
}

void *customer(void *arg)
{
    int nolock = 0;
    int ret, nread;

    while(time(NULL) < end_time)
    {
        sem_wait(&full);
        sem_wait(&mutex);

        memset(buf_r, 0, sizeof(buf_r));

        if((nread = read(fd, buf_r, 100)) == -1)
        {
            if(errno == EAGAIN){
                printf("no data yet\n");
            }
        }

        printf("read %s from FIFO\n", buf_r);
        sem_post(&avail);
        sem_post(&mutex);
        sleep(1);
    }
}

int main()
{
    pthread_t thrd_prd_id, thrd_cst_id; 
    pthread_t mon_th_id;

    int ret;
    end_time = time(NULL) + 30;
    memset(buf_r, 0, sizeof(buf_r));

    //创建管道 
    if((mkfifo(FIFO, O_CREAT| O_EXCL) < 0) && (errno != EEXIST))
    {
        printf("pipe create error\n");
        exit(1);
    }
    //打开管道
    fd = open(FIFO, O_RDWR| O_NONBLOCK, 0);
    if(fd == -1)
    {
        perror("open error!\n");
        exit(1);
    }

    //信号量 初始化 
    ret = sem_init(&mutex, 0, 1);
    ret += sem_init(&avail, 0, BUFFER_SIZE);
    ret += sem_init(&full, 0, 0);
    if(ret != 0)
    {
        printf("Any semaphore initialization failed\n");
        return ret;
    }

    //创建生产者线程
    ret = pthread_create(&thrd_prd_id, NULL, producer, NULL);
    if(ret != 0)
    {
        printf("Create producer thread error\n");
        return ret; 
    } 
    //创建消费者线程
    ret = pthread_create(&thrd_cst_id, NULL, customer, NULL);
    if(ret != 0)
    {
        printf("Create producer thread error\n");
        return ret;
    } 

    pthread_join(thrd_prd_id, NULL);
    pthread_join(thrd_cst_id, NULL);

    close(fd);

    return 0;
}
生产者消费者问题是指在多线程环境下,生产者消费者之间共享一个固定大小的缓冲区,生产者向缓冲区中生产数据,而消费者从缓冲区中消费数据。生产者消费者之间需要进行同步,以避免生产者向已满的缓冲区中生产数据,或者消费者从空的缓冲区中消费数据的情况。在这个问题中,pv操作是一种原语操作,用于实现同步。 具体来说,pv操作包括两个操作:P操作和V操作。P操作用于获取资源,V操作用于释放资源。在生产者消费者问题中,可以使用两个信号量来实现同步,一个信号量用于表示缓冲区中空闲的缓冲区数量,另一个信号量用于表示缓冲区中已经填充的缓冲区数量。 下面是一个使用pv操作解决生产者消费者问题的示例代码: ```python from threading import Semaphore, Thread import time BUFFER_SIZE = 10 buffer = [None] * BUFFER_SIZE mutex = Semaphore(1) empty = Semaphore(BUFFER_SIZE) full = Semaphore(0) def producer(): global buffer for i in range(20): empty.acquire() mutex.acquire() buffer[i % BUFFER_SIZE] = i print(f"Producer produced item {i}") mutex.release() full.release() time.sleep(0.5) def consumer(): global buffer for i in range(20): full.acquire() mutex.acquire() item = buffer[i % BUFFER_SIZE] buffer[i % BUFFER_SIZE] = None print(f"Consumer consumed item {item}") mutex.release() empty.release() time.sleep(0.5) t1 = Thread(target=producer) t2 = Thread(target=consumer) t1.start() t2.start() t1.join() t2.join() ``` 在这个示例代码中,使用了三个信号量:mutex、empty和full。mutex用于实现互斥,empty用于表示缓冲区中空闲的缓冲区数量,full用于表示缓冲区中已经填充的缓冲区数量。在生产者线程中,首先获取empty信号量,表示有空闲的缓冲区可以使用,然后获取mutex信号量,表示对缓冲区进行操作,将数据写入缓冲区,最后释放mutex信号量和full信号量。在消费者线程中,首先获取full信号量,表示有数据可以消费,然后获取mutex信号量,表示对缓冲区进行操作,将数据从缓冲区中读取,最后释放mutex信号量和empty信号量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值