生产者和消费者模型(简单版本)

综述:
在整个模型中,有三个比较关键的对象:生产者、消费者、和容器。其中生产者被用来生产资源,可以是单线程也可以是多线程;消费者被用来消耗资源也可以是单线程或者多线程;无论是生产还是消费都把容器当做一个介质(中间的交换者的角色)。下面的代码中用多线程进行生产和消费,容器使用链表,链表的操作是头插和头删。详见代码注释
code:

/*
生产者消费者模型(粗略版本)
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
//创建一个互斥量
pthread_mutex_t mutex;
struct Node
{
    int num;
    struct Node* next;
};
//头结点
struct Node* head = NULL;

void * producer(void* arg){
    //不断创建新节点添加到链表中,头插
    while (1)
    {
        pthread_mutex_lock(&mutex);
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num = rand() % 1000;
        printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
        pthread_mutex_unlock(&mutex);
        usleep(100); 
    }
    
    return NULL;
}
void * customer(void* arg){
    while (1)
    {
        //先不考虑容器为空的条件,头删
        pthread_mutex_lock(&mutex);
        struct Node* temp = head;
        // 判断是否有数据
        if(head != NULL){
            //有数据
            head = head->next;
            printf("del node , num : %d, tid : %ld\n",temp->num, pthread_self());
            free(temp);
            pthread_mutex_unlock(&mutex);
            usleep(100);//睡眠100微妙
        }else
        {
            pthread_mutex_unlock(&mutex);
        }
    } 
    return NULL;
}

int main(){

    pthread_mutex_init(&mutex, NULL);

    //创建5个生产者线程,5个消费者线程,用链表来作为容器(添加数据采用头插法)
    pthread_t ptids[5], ctids[5];

    for(int i = 0; i < 5; ++i){
        pthread_create(&ptids[i], NULL, producer, NULL);
        pthread_create(&ctids[i], NULL, customer, NULL);
    }
    for(int i = 0; i < 5; ++i){
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while (1)
    {
        sleep(10);
    }
    pthread_mutex_destroy(&mutex);//这个地方不能立马销毁
    pthread_exit(NULL);//退出子线程
   
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值