条件变量:[单生产者/单消费者]单链表的插入和删除
typedef struct node{//声明链表类型
int data;
struct node* next;
}LNode;
LNode* head=NULL; //临界资源:链表的头节点
pthread_mutex_t mutex;
pthread_cond_t cond;
void* producer(void* arg){
while(1){
LNode* node=(LNode*)malloc(sizeof(LNode)); //创建新的节点node
node->data=rand()%100;
pthread_mutex_lock(&mutex);
node->next=head; //将node采用头插法插入链表
head=node;
printf(" produce node=%d\n",node->data);
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
pthread_cond_signal(&cond); //插入node后,唤醒等待的线程去消费链表
}
return NULL;
}
void* customer(void* arg){
while(1){
pthread_mutex_lock(&mutex);
while(head==NULL){ //if(head==NULL) 如果链表为NULL,则一直阻塞
pthread_cond_wait(&cond,&mutex);
}
//采用头删法删除节点
LNode* delNode=head;
head=head->next; //delete head
printf("delete node=%d\n",delNode->data);
free(delNode);
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
return NULL;
}
int main(){
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,producer,NULL);
pthread_create(&tid2,NULL,customer,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}