生產者消費者模型

我們在這裏定義一個生產者消費這模型,及供求關係

  • 生產者在沒有貨時候,買家是不能買到東西的
  • 消費者之間存在原子性操作
  • 總的條件因素應該就是這樣了,抱着這個操作,我們完成一個試着完成一個模型。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define CONSUMERS_COUNT 2
#define PRODUCERS_COUNT 2
struct msg
{
	struct msg *next;   
	int num;
};
struct msg *head = NULL;
pthread_cond_t cond; 
pthread_mutex_t mutex;
pthread_t threads[CONSUMERS_COUNT + PRODUCERS_COUNT];
void *consumer(void *p) 
{ 
	int num = *(int*)p;    
	free(p);  
	struct msg *mp;  
	for (;;)
	{ 
		pthread_mutex_lock(&mutex);
		while (head == NULL)  
		{
			printf("%d begin wait a condition...\n", num);
			pthread_cond_wait(&cond, &mutex); 
		}     
		printf("%d end wait a condition...\n", num);   
		printf("%d begin consume product...\n", num);
		mp = head;
		head = mp->next; 
		pthread_mutex_unlock(&mutex);
		printf("Consume %d\n", mp->num); 
		free(mp);
		printf("%d end consume product...\n", num);
		sleep(rand() % 5); } 
}
void *producer(void *p)
{
	struct msg *mp; 
	int num = *(int*)p; 
	free(p);
	for (;;) 
	{
		printf("%d begin produce product...\n", num); 
		mp = (struct msg*)malloc(sizeof(struct msg));   
		mp->num = rand() % 1000 + 1;  
		printf("produce %d\n", mp->num);   
		pthread_mutex_lock(&mutex);   
		mp->next = head; 
		head = mp;     
		printf("%d end produce product...\n", num); 
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);  
		sleep(rand() % 5);
	}
}
int main(void) 
{
	srand(time(NULL));
	pthread_cond_init(&cond, NULL);   
	pthread_mutex_init(&mutex, NULL);
	int i; 
	for (i = 0; i<CONSUMERS_COUNT; i++) 
	{
		int *p = (int*)malloc(sizeof(int)); 
		*p = i;   
		pthread_create(&threads[i], NULL, consumer, (void*)p); 
	}
	for (i = 0; i<PRODUCERS_COUNT; i++)
	{ 
		int *p = (int*)malloc(sizeof(int));     
		*p = i;    
		pthread_create(&threads[CONSUMERS_COUNT + i], NULL, producer, (void*)p); 
	}
	for (i = 0; i<CONSUMERS_COUNT + PRODUCERS_COUNT; i++)    
		pthread_join(threads[i], NULL);
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
}

  • 我們主要還是需要記住原子性的約束條件和接口函數不要寫錯,記住變量加鎖,解鎖條件。
  • ==其他的實在也不知道需要說一些什麼了。
    檢驗一些結果吧。
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章