typedef struct node{
struce node* next;
int val;
}Node;
Node* head=NULL;//头结点初始化为空
pthread_mutex_t mutex;
pthread_cond_t cond;
void *producer(void *arg){
while(1){
Node* pNew=(Node*) malloc(sizeof(Node));//生产一个新节点
pNew->val=rand()%1000;
//开始把生产的节点加入到链表中
pthread_mutex_lock(&mutex);
//采用头插法
pNew->next=head;
head=pNew;
//输出产品信息
printf("Producer's id=%lu,pNew->val=%d\n",pthread_self(),pNew->data);
//插入完成后解锁
pthread_mutex_unlock(&mutex);
//解锁后通知消费者
pthread_cond_signal(&cond);
sleep(rand()%3);
}
return NULL;
}
void *consumer(void *arg){
while(1){
//消费前,先尝试解锁
pthread_mutex_unlock(&mutex);
if(head==NULL){//还没有产品时
pthread_cond_wait(&cond,&mutex);//cond满足时,解除阻塞
}
//有产品时,开始消费
Node* pDel=head;
head=head->next;
printf("consumer's id=%lu,pNew->val=%d\n",pthread_self(),pNew->data);
free(pDel);
pthread_mutex_unlock(&mutex);
}
return NULL;
}