> 文章列表 > day9 条件变量的基本使用

day9 条件变量的基本使用

day9 条件变量的基本使用

目录

条件变量


条件变量

应用场景:生产者消费问题,是线程同步的一种手段;

必要性:为了实现等待某个资源,让线程休眠,提高运行效率;

等待资源:

//1、一直等待资源
int pthread_cond_wait(pthread_con_t *restrict cond,pthrad_mutex_t *restrict mutex);
//2、等待资源,只等待一段时间
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex,const struct timespec *restrict mutex);

释放资源:

int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

使用步骤:

1、初始化

静态初始化

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t mutex = PTHREAD_MUTEX_INITIALIZER;

 动态初始化

pthread_cond_init(&cond);

生产资源线程:

pthread_mutex_lock(&mutex);

开始生产资源:

1、通知一个消费线程

pthread_cond_signal(&cond);    
pthread)mutex_unlock(&mutex);

2、广播通知多个消费线程

pthread_cond_broadast(&cond);
pthread_mutex_unlock);

消费者线程:

pthread_mutex_lock(&mutex);
while (如果没有资源){           //防止惊群效应
pthread_cond_wait(&cond, &mutex); 
}
//有资源了,消费资源
pthread_mutex_unlock(&mutex);  

完整代码:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>pthread_cond_t hastaxi = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;struct taxi{struct taxi *next;int num;
};struct taxi *head = NULL;//生产者线程
void *taxiarv(void *arg) {printf("taxi arrived thread\\n");pthread_detach(pthread_self());struct taxi *tx;int i = 1;while(1) {tx = malloc(sizeof(struct taxi));tx->num = i++;printf("text %d comming\\n",tx->num);pthread_mutex_lock(&lock);tx->next = head;head = tx;pthread_cond_signal(&hastaxi);pthread_mutex_unlock(&lock);sleep(1);}pthread_exit(0);
}
//消费者线程
void *taketaxi(void *arg) {printf("take taxi thread\\n");pthread_detach(pthread_self());struct taxi *tx;while(1) {pthread_mutex_lock(&lock);while(head == NULL) {pthread_cond_wait(&hastaxi, &lock);}tx = head;head = tx->next;printf("take taxi %d\\n", tx->num);free(tx);pthread_mutex_unlock(&lock);}pthread_exit(0);
}int main() {pthread_t tid1, tid2;pthread_create(&tid1, NULL, taxiarv, NULL);pthread_create(&tid2, NULL, taketaxi, NULL);while (1) {sleep(1);}}

执行结果:

注意:

1、pthread_cond_wait(&cond, &mutex),在没有资源等待时是先unlock 休眠等资源到了再lock,所以pthread_cond_wait  和 pthread_mutex_lock 必须配对使用。

2、 如果pthread_cond_signal或者pthread_cond_broadcast 早于 pthread_cond_wait ,则有可能会丢失信号。

3、pthead_cond_broadcast 信号会被多个线程收到,这叫线程的惊群效应。所以需要加上判断条件while循环。