#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
//線程同步
pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
typedef struct node
{
int data;
struct node *next;
}Node;
//指針
Node *head=NULL;
/*
producer:
consumer:
*/
void *consumer(void *arc){
while(1){
//判斷是否有東西
//如果爲空則阻塞
pthread_mutex_lock(&mylock);
if(head == NULL){
//阻塞等待有東西
//自動解鎖條件不滿足的
pthread_cond_wait(&cond,&mylock);
//枷鎖嗎?
//acontinue;
}
//吃東西訪問共享數據刪除節點
Node *pdel= head;
head = head->next;
printf("-------consumer:%#X spend %d\n",pthread_self(),pdel->data);
free(pdel);
pthread_mutex_unlock(&mylock);
sleep(1);
}
pthread_exit((void *)0);
}
void *producer(void *arc){
while(1){
//創建節點
Node *pnew =(Node *)malloc(sizeof(Node));
//插入節點初始化
pnew->data = rand() % 1000; //0-999
//枷鎖
pthread_mutex_lock(&mylock);
//頭插法
pnew->next = head;
head = pnew;
printf("-------producer:%#X produce %d\n",pthread_self(),pnew->data);
pthread_mutex_unlock(&mylock);
//通知消費者喚醒一個線程
pthread_cond_broadcast(&cond);//喚醒所有線程
// pthread_cond_signal(&cond);
//printf("lmj\n");
sleep(rand()%3);
}
//通知消費者
pthread_exit((void *)1);
}
int main(int argc, char const *argv[])
{
pthread_t tid1,tid2;
pthread_mutex_init(&mylock,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&tid1,NULL,producer,NULL);
pthread_create(&tid2,NULL,consumer,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mylock);
pthread_cond_destroy(&cond);
//sleep(10);
return 0;
}
生產者消費者模型Linux c語言
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.