1、编程要求:
2、运行结果
3、代码实现
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
struct msg{
struct msg *next;
int num;
};
struct msg *head;
//定义条件变量
pthread_mutex_t m;
//定义互斥锁
pthread_cond_t c;
void *producer(void *p);
void *consumer(void *p);
int main(void)
{
pthread_t pid,tid;
srand(time(NULL));
//初始化条件变量//初始化互斥锁
pthread_mutex_init(&m,NULL);
pthread_cond_init(&c,NULL);
//创建生产者消费者进程
pthread_create(&pid,NULL,producer,NULL);
pthread_create(&tid,NULL,consumer,NULL);
//回收线程
pthread_join(pid,NULL);
pthread_join(tid,NULL);
return 0;
}
//生产者
void *producer(void *p)//????
{
struct msg *mp;
while(1)
{
mp=malloc(sizeof(struct msg));
//produce
mp->num=rand()%1000+1;
printf("produce\t---%d\n",mp->num);
//加锁
pthread_mutex_lock(&m);
//添加产品
mp->next=head;
head=mp;
//解锁
pthread_mutex_unlock(&m);
//唤醒进程
pthread_cond_signal(&c);
sleep(rand()%5);
}
}
//消费者
void *consumer(void *p)
{
struct msg *mp;
while(1)
{
//加锁
pthread_mutex_lock(&m);
//(1)消费不到一直阻塞等待
while(head==NULL)
{
pthread_cond_wait(&c,&m);
}
//(2)消费得到
mp=head;
head=head->next;
//解锁
pthread_mutex_unlock(&m);
printf("consumer\t---%d\n",mp->num);
//释放已经消费产品空间
free(mp);
sleep(rand()%5);
}
}