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