目录
生产者消费者问题:生产者不能在容器满了继续生成,消费者不能在容器为空的时候消费
1.条件变量函数原型
条件变量的类型 pthread_cond_t
pthread_cond_init
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
-功能:初始化
pthread_cond_destroy
int pthread_cond_destroy(pthread_cond_t *cond);
-功能:回收资源
pthread_cond_wait
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
-功能:等待,调用了该函数,线程会阻塞。当这个函数调用阻塞的时候,会对互斥锁进行解锁,当不阻塞的,继续向下执行,会重新加锁。
pthread_cond_timedwait
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
-功能:等待多少时间,调用了这个函数,线程会阻塞,知道指定的时间结束。
pthread_cond_signal
int pthread_cond_signal(pthread_cond_t *cond);
-功能:唤醒一个或多个等待的线程
pthread_cond_broadcast
int pthread_cond_broadcast(pthread_cond_t *cond);
-功能:唤醒所有的等待的线程
2.案例源码
通过设置条件变量来在没有资料的时候消费者等待生产者来生成
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
//创建互斥量
pthread_mutex_t mutex;
//创建条件变量
pthread_cond_t cond;
struct Node{
int num;
struct Node *next;
};
//头节点
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("add node, num %d,tid :%ld\n",newNode->num,pthread_self());
//只要生成了一个,就通知消费者消费
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("del node, num:%d,tid:%ld\n",tmp->num,pthread_self());
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);
//创建5个生产者线程和5个消费者线程
pthread_t ptids[5],ctids[5];
for(int i=0;i<5;i++){
pthread_create(&ptids[i],NULL,producer,NULL);
pthread_create(&ctids[i],NULL,customer,NULL);
}
for(int i=0;i<5;i++){
pthread_detach(ptids[i]);
pthread_detach(ptids[i]);
}
while(1){
sleep(10);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return 0;
}