Linux編程:條件變量的使用(生產者消費者)

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);
	}
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章