条件变量通常与互斥锁一同使用,在本案例中,有生产者、消费者以及容器(链条),由于单单使用互斥锁进行数据生产和消费时,若缓冲区(容器)内数据为空时会浪费资源,所以使用条件变量来使得系统的资源得到最大化利用,当缓冲区为空时,消费者给生产者发送信号并把互斥锁打开,生产者接受到信号就生产数据放入缓冲区(容器),再返回信号给消费者,消费者再上锁
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
struct Node{
int num;
struct Node *next;
};
pthread_mutex_t mutex;
pthread_cond_t cond;
struct Node * head = NULL;
void* producer(void* arg){
while(1){
pthread_mutex_lock(&mutex);
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->next = head;
head = newNode;
newNode->num = rand()%1000;
printf("produce tids:%ld num:%d\n",pthread_self(),newNode->num);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
usleep(100);
}
return NULL;
}
void* customer(void* arg){
while(1){
pthread_mutex_lock(&mutex);
struct Node * tmp = head;
if(head!=NULL){
head = head->next;
printf("customer tids:%ld num:%d\n",pthread_self(),tmp->num);
free(tmp);
pthread_mutex_unlock(&mutex);
usleep(100);
}else{
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
}
}
return NULL;
}
int main(){
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_t pids[5],cids[5];
for(int i=0;i<5;i++){
pthread_create(&pids[i],NULL,producer,NULL);
pthread_create(&cids[i],NULL,customer,NULL);
}
for(int i=0;i<5;i++){
pthread_detach(pids[i]);
pthread_detach(cids[i]);
}
while(1) {
sleep(10);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return 0;
}