代碼實現:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
typedef struct Node{
int value;
struct Node* next;
}Node;
Node* alloc(int value)
{
Node* pTmp = (Node*) malloc(sizeof(Node));
pTmp->value = value;
pTmp->next = NULL;
return pTmp;
}
void Free(Node* pTmp)
{
if(pTmp)
free(pTmp);
pTmp = NULL;
}
void InitList(Node** pHead)
{
*pHead = (Node*) malloc(sizeof(Node));
(*pHead)->next = NULL;
}
void PushFront(Node* pHead, int value)
{
Node* pTmp = alloc(value);
pTmp->next = pHead->next;
pHead->next = pTmp;
}
void PopFront(Node* pHead)
{
Node* pTmp = pHead->next;
if(pTmp)
{
pHead->next = pTmp->next;
Free(pTmp);
}
}
void DestroyList(Node** pHead)
{
while((*pHead)->next)
{
PopFront(*pHead);
}
Free(*pHead);
}
void PrintList(Node* pHead)
{
while(pHead->next)
{
printf("%d ", pHead->next->value);
pHead = pHead->next;
}
printf("\n");
}
int isEmpty(Node* pHead)
{
if(pHead->next)
return 0;
return 1;
}
int SizeList(Node* pHead)
{
int count = 0;
pHead = pHead->next;
while(pHead)
{
count++;
pHead = pHead->next;
}
return count;
}
//創建鏈表
Node* pHead;
//創建條件變量
pthread_cond_t need_prod = PTHREAD_COND_INITIALIZER;
//創建互斥鎖
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
//生產者
void *product(void *arg)
{
while(1){
sleep(1);
//申請鎖
pthread_mutex_lock(&lock);
int data = rand() % 123;
PushFront(pHead, data);
printf("生產者生產完成: %d\n", data);
//釋放鎖
pthread_mutex_unlock(&lock);
//喚醒消費者線程
pthread_cond_signal(&need_prod);
}
}
//消費者
void *consumer(void *arg)
{
while(1){
//申請鎖
pthread_mutex_lock(&lock);
while(isEmpty(pHead))
{
printf("生產者沒有生產完畢,消費者等待\n");
//如果鏈表中爲空,消費者就要進行等待,等生產者生產完成後喚醒自己
//在進入等待隊列時,它會釋放鎖資源,以便其他進程進行生產,在出等待隊列時,它會恢復鎖的狀態
pthread_cond_wait(&need_prod, &lock);
}
printf("消費者消費完畢: %d\n", pHead->next->value);
PopFront(pHead);
//釋放鎖
pthread_mutex_unlock(&lock);
}
}
int main()
{
InitList(&pHead);
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, product, NULL);
pthread_create(&thread2, NULL, consumer, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
//銷燬互斥鎖
pthread_mutex_destroy(&lock);
//銷燬條件變量
pthread_cond_destroy(&need_prod);
DestroyList(&pHead);
return 0;
}
運行結果: