操作系统 - C语言实现生产者消费者问题

同步互斥问题 - 生产者消费者问题



问题描述:

有多个进程:多个生产者进程和多个消费者进程共享一个初始为空、固定大小为n的缓存(缓冲区)。生产者的工作是制造数据,只有缓冲区没满时,生产者才能把消息放入到缓冲区,否则必须等待; 同时,只有缓冲区不空时,消费者才能从中取出消息,一次消费一段数据(即将其从缓存中移出),否则必须等待。由于缓冲区是临界资源,它只允许一个生产者放入消息,或者一个消费者从中取出消息,同时只允许一个生产者进行制造,多个生产者不能同时制造,也只允许一个消费之进行消费,多个消费者不能同时进行消费。

主要问题:
  • 当缓冲为空的时候,消费者不能消费,必须等待
  • 当缓存为满的时候,生产者不能生产,必须等待
  • 生产者消费者之间必须互斥
实现思路:
  1. 设置三个信号量:empty (以记录有多少空位)、full (以记录有多少满位)以及mutex
    (二进制信号量或互斥信号量,以保护对缓冲插入与删除的操作)

  2. 当信号量empty为0的时候,此时有限缓存已满,生产者必须等待,当信号量full为0的时候,此时有限缓存为空,消费者无法进行消费,必须等待

  3. 信号量mutex使得各个线程之间互斥,每次只允许一个线程进入临界区,一旦有线程进入自己的临界区,其余线程必须等待

  4. 有限缓存区为循环队列,尾部插入新的产品,头部产品先被消耗

实现:
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <sys/types.h>
# include <pthread.h>
# include <semaphore.h>
# include <string.h>
# include <unistd.h>

#define BUFFER_SIZE 5
typedef int buffer_item;

//semaphores
sem_t empty, full, mutex;

//buffer
buffer_item buffer[BUFFER_SIZE];

int in, out;

//存储数据的结构体
struct data {
    int id;
    int opTime;
    int lastTime;
    int productId;
};

//有限缓存插入--生产
int insert_item(buffer_item item) {
    /* insert item into buffer */
    buffer[out] = item;
    out = (out + 1) % BUFFER_SIZE;
    return 0;
}

//有限缓存删除--消费
int remove_item(buffer_item *item) {
    /* remove an object from buffer and then place it in item */
    *item = buffer[in];
    in = (in + 1) % BUFFER_SIZE;
    return 0;   
}

//生产者
void *producer(void* param) {
    int productId = ((struct data*)param)->productId;
    int lastTime = ((struct data*)param)->lastTime;
    int opTime = ((struct data*)param)->opTime;
    int id = ((struct data*)param)->id;

    free(param);

    sleep(opTime);
    sem_wait(&empty);
    sem_wait(&mutex);

    /* critical section */
    //add a item
    insert_item(productId);
    sleep(lastTime);
    printf("Thread %d: Producer produce %d\n", id, productId);

    sem_post(&mutex);
    sem_post(&full);
    pthread_exit(0);
}

//消费者
void *consumer(void* param) {
    int lastTime = ((struct data*)param)->lastTime;
    int opTime = ((struct data*)param)->opTime;
    int id = ((struct data*)param)->id;

    free(param);

    sleep(opTime);
    sem_wait(&full);
    sem_wait(&mutex);

    /* critical section */
    //remove a item
    buffer_item item;
    remove_item(&item);
    sleep(lastTime);
    printf("Thread %d: Consumer consume %d\n", id, item);

    sem_post(&mutex);
    sem_post(&empty);
    pthread_exit(0);
}

int main() {
    //pthread
    pthread_t tid; // the thread identifier

    pthread_attr_t attr; //set of thread attributes

    /* get the default attributes */
    pthread_attr_init(&attr);

    //initial the semaphores
    sem_init(&mutex, 0, 1);
    sem_init(&empty, 0, BUFFER_SIZE);
    sem_init(&full, 0, 0);

    in = out = 0;

    int id = 0;
    while(scanf("%d", &id) != EOF) {
        char role;      //producer or consumer
        int opTime;     //operating time
        int lastTime;   //run time
        int productId;  //product id
        scanf("%c%d%d", &role, &opTime, &lastTime);
        struct data* d = (struct data*)malloc(sizeof(struct data));
        d->id = id;
        d->opTime = opTime;
        d->lastTime = lastTime;
        if(role == 'P') {
            scanf("%d", &productId);
            d->productId = productId;
            pthread_create(&tid, &attr, producer, d);

        }
        else if(role == 'C')
            pthread_create(&tid, &attr, consumer, d);
    }

    //释放信号量
    sem_destroy(&mutex);
    sem_destroy(&empty);
    sem_destroy(&full);

    return 0;
}
测试:

测试数据:

1 C 3 5
2 P 4 5 1
3 C 5 2
4 C 6 5
5 P 7 3 2
6 P 8 4 3

输出结果:
生产者消费者问题输出结果

  • 12
    点赞
  • 168
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
下面是一个简单的生产者消费者模型的C语言代码,使用消息队列实现进程间通信: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/msg.h> #include <sys/wait.h> #define MAX_MSG_SIZE 64 #define MAX_MSG_NUM 10 struct msgbuf { long mtype; char mtext[MAX_MSG_SIZE]; }; int main() { int msgid; pid_t pid; // 创建消息队列 msgid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT); if (msgid == -1) { perror("msgget"); exit(EXIT_FAILURE); } // 创建生产者进程 pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (pid == 0) { // 生产者进程 int i; struct msgbuf msg; for (i = 0; i < MAX_MSG_NUM; i++) { // 构造消息 msg.mtype = 1; sprintf(msg.mtext, "Message %d from producer", i + 1); // 发送消息 if (msgsnd(msgid, &msg, MAX_MSG_SIZE, 0) == -1) { perror("msgsnd"); exit(EXIT_FAILURE); } printf("Producer sent: %s\n", msg.mtext); } exit(EXIT_SUCCESS); } // 创建消费者进程 pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (pid == 0) { // 消费者进程 int i; struct msgbuf msg; for (i = 0; i < MAX_MSG_NUM; i++) { // 接收消息 if (msgrcv(msgid, &msg, MAX_MSG_SIZE, 0, 0) == -1) { perror("msgrcv"); exit(EXIT_FAILURE); } printf("Consumer received: %s\n", msg.mtext); } exit(EXIT_SUCCESS); } // 等待子进程退出 wait(NULL); wait(NULL); // 删除消息队列 if (msgctl(msgid, IPC_RMID, NULL) == -1) { perror("msgctl"); exit(EXIT_FAILURE); } return 0; } ``` 以上代码中,首先使用`msgget`系统调用创建一个消息队列,然后创建一个生产者进程一个消费者进程生产者进程循环发送10条消息到消息队列中,消费者进程循环从消息队列中接收消息并输出。最后等待子进程退出,然后使用`msgctl`系统调用删除消息队列。 需要注意的是,在实际生产环境中,需要考虑更复杂的情况,如多个生产者消费者同时访问消息队列,需要使用信号量等机制进行进程间同步和互斥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值