Linux 下多线程的消费者-生产者模型

xiaoxiao2021-02-28  88

消费者-生产者模型

    所谓这个模型指在ipc时,由扮演的生产者进程产生数据,由扮演消费者的进程去拿走数据。     这个模型 是由3种关系俩种角色一个场景所描述而成。     三种关系指:     消费者-消费者  --->  互斥     生产者-生产者  --->  互斥     消费者-生产者  --->  同步与互斥     俩种角色指:     消费者与生产者      一个场景:      临界区:多个进程看到的同一份临界资源。 单消费-单产生模型代码     基于链表实现(应用了互斥锁和条件变量) #ifndef CON_PROC_H #define CON_PROC_H #include<stdio.h> #include<stdlib.h> #include<pthread.h> typedef int datatype; typedef struct list{ int _value; struct list * _pNext; } Node,*PNode,**position; PNode head; void Insert(datatype value,position p) { PNode NewNode=(Node*)malloc(sizeof(Node)); if(NewNode==NULL) { perror("malloc"); return ; } if(*p==NULL) { NewNode->_value=value; NewNode->_pNext=NULL; *p=NewNode; return ; } NewNode->_value=value; NewNode->_pNext=*p; *p=NewNode; } int empty() { return head==NULL; } void pop_front(int*p) { if(empty()) { printf("List is empty\n"); return ; } PNode del=head; *p=head->_value; head=head->_pNext; free(del); } void Delete_List() { PNode del; while(head) { del=head; head=head->_pNext; free(del); } } #endif #include "con_prod.h" static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond=PTHREAD_COND_INITIALIZER; PNode head=NULL; void* product(void*i) { int goods=0; while(1) { sleep(1); pthread_mutex_lock(&lock); goods=rand()
转载请注明原文地址: https://www.6miu.com/read-51552.html

最新回复(0)