一切想表达的都在代码和注释里了
只需要两分钟你就能看懂
源码
//利用条件变量实现生产者,消费者问题
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//定义一把锁
pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER;
//定义一个条件
pthread_cond_t cond1=PTHREAD_COND_INITIALIZER;
typedef struct table{
struct table *next;
int num;
} ST;
//定义头节点
ST *head;
void producer(){
while (1){
ST *food;
food=malloc(sizeof(struct table));
pthread_mutex_lock(&mutex1);//对桌子加锁
food->num=rand()%1000+1;//随机生成一个数
//头插法将生产的数据发送到桌子上
food->next=head;
head=food;
printf("------producer is: %d\n",food->num);
pthread_mutex_unlock(&mutex1);//释放锁
pthread_cond_signal(&cond1);//发送已经生产的条件
sleep(rand()%3);
}
}
void consumer(){
while (1){
ST *food;
pthread_mutex_lock(&mutex1);
if (head==NULL){
pthread_cond_wait(&cond1,&mutex1);//桌子上没有东西,就阻塞
}
food=head;
head=NULL;
printf("------consumer is: %d\n",food->num);
pthread_mutex_unlock(&mutex1);
free(food);
sleep(rand()%3);
}
}
int main(void){
//创建两个线程,生产者,消费者
pthread_t tid1,tid2;
while ((pthread_create(&tid1,NULL,(void *)producer,NULL))!=0);
while ((pthread_create(&tid2,NULL,(void *)consumer,NULL))!=0);
//回收线程
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
实验结果
(最好是根据实验现象分析其中的原理)