> 文章列表 > 条件变量

条件变量

条件变量

基本概念: 

        条件变量利用线程间共享的变量进行同步的一种机制,是在多线程程序中用来实现"等待–>唤醒"逻辑常用的方法,用于维护一个条件(与是条件变量不同的概念),线程可以使用条件变量来等待某个条件为真,注意理解并不是等待条件变量为真。

        当条件不满足时,线程将自己加入等待队列,同时释放持有的互斥锁; 当一个线程唤醒一个或多个等待线程时,此时条件不一定为真(虚假唤醒)。

  • 条件变量本身不是锁!但它也可以造成线程阻塞。通常与互斥锁配合使用。给多线程提供一个会合的场所。
  • 条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。

 主要应用函数:

  • pthread_cond_init函数
  • pthread_cond_destroy函数
  • pthread_cond_wait函数
  • pthread_cond_timedwait函数
  • pthread_cond_signal函数
  • pthread_cond_broadcast函数

 以上6 个函数的返回值都是:成功返回0, 失败直接返回错误号。

        pthread_cond_t类型      用于定义条件变量

        pthread_cond_t cond;

pthread_cond_init函数

初始化一个条件变量

        int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);                 

        参2:attr表条件变量属性,通常为默认值,传NULL即可

        也可以使用静态初始化的方法,初始化条件变量:

                pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

 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);

函数作用:

  1. 阻塞等待条件变量cond(参1)满足 
  2. 释放已掌握的互斥锁(解锁互斥量)相当于pthread_mutex_unlock(&mutex); 以上两步为一个原子操作。
  3. 当被唤醒,pthread_cond_wait函数返回时,解除阻塞并重新申请获取互斥锁pthread_mutex_lock(&mutex);

 pthread_cond_timedwait函数

限时等待一个条件变量

        int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);

        参3:参看man sem_timedwait函数,查看struct timespec结构体。

                struct timespec {

                                time_t tv_sec;          /* seconds */ 秒

                                long   tv_nsec;      /* nanosecondes*/ 纳秒

                }                                                                        

        形参 abstime:绝对时间。                                                                                      

 pthread_cond_signal函数

唤醒至少一个阻塞在条件变量上的线程

int pthread_cond_signal(pthread_cond_t *cond);

 pthread_cond_broadcast函数

唤醒全部阻塞在条件变量上的线程

int pthread_cond_broadcast(pthread_cond_t *cond);

 生产者消费者条件变量模型

        线程同步典型的案例即为生产者消费者模型,而借助条件变量来实现这一模型,是比较常见的一种方法。假定有两个线程,一个模拟生产者行为,一个模拟消费者行为。两个线程同时操作一个共享资源(一般称之为汇聚),生产向其中添加产品,消费者从中消费掉产品。

https://www.bilibili.com/video/BV1KE411q7ee?p=178&spm_id_from=pageDriver&vd_source=d239c7cf48aa4f74eccfa736c3122e65https://www.bilibili.com/video/BV1KE411q7ee?p=178&spm_id_from=pageDriver&vd_source=d239c7cf48aa4f74eccfa736c3122e65

/*借助条件变量模拟 生产者-消费者问题*/
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>/*链表作为共享数据,需要被互斥量保护*/
struct msg {struct msg *next;int num;
};struct msg *head;/*静态初始化 一个条件变量 和 一个互斥量*/
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;void *consumer(void *p)
{struct msg *mp;while(1) {pthread_mutex_lock(&lock);while (head == NULL) {           //头指针为空,说明没有节点  可以为if吗pthread_cond_wait(&has_product, &lock); //阻塞等待}mp = head;      head = mp->next;    			//模拟消费掉一个产品pthread_mutex_unlock(&lock);printf("-Consume ---%d\\n", mp->num);free(mp); //mallocsleep(rand() % 5); //给对端获取CPU的机会}
}
void *producer(void *p)
{struct msg *mp;while (1) {mp = malloc(sizeof(struct msg)); //freemp->num = rand() % 1000 + 1;        //模拟生产一个产品printf("-Produce -----------------%d\\n", mp->num);pthread_mutex_lock(&lock);mp->next = head; //头插法head = mp;pthread_mutex_unlock(&lock);pthread_cond_signal(&has_product);  //将等待在该条件变量上的一个线程唤醒sleep(rand() % 5);}
}
int main(int argc, char *argv[])
{pthread_t pid, cid;srand(time(NULL));pthread_create(&pid, NULL, producer, NULL);pthread_create(&cid, NULL, consumer, NULL);pthread_join(pid, NULL);pthread_join(cid, NULL);return 0;
}		

一个生产者,多个消费者

/*借助条件变量模拟 生产者-消费者问题*/
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include<errno.h>void err_thread(int ret, char *str)
{if(ret != 0){fprintf(stderr, "%s\\n", str, strerror(ret));pthread_exit(NULL);}
}struct msg
{int num;struct msg *next;
};struct msg *head;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //定义并初始化互斥量
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER; //定义并初始化条件变量void *producer(void *arg)
{while(1){struct msg *mp = malloc(sizeof(struct msg));mp->num = rand()%1000+1;           //模拟生产一个数据printf("---producer---------- %d\\n", mp->num);pthread_mutex_lock(&mutex); //写公共区域  把数据加入公共区域,需要加锁mp->next = head; //头插法head = mp;pthread_mutex_unlock(&mutex);  //解锁pthread_cond_signal(&has_data);  //唤醒阻塞在条件变量has_data上的线程,即生产者sleep(rand()%3);}return NULL;
}void *consumer(void *arg)
{while(1){struct msg *mp;pthread_mutex_lock(&mutex); //加锁  互斥量//if(head == NULL){ //一个生产者一个消费者,可用ifwhile(head == NULL){ //多个消费者,要用whilepthread_cond_wait(&has_data, &mutex); //阻塞等待条件变量,解锁}                                         //pthread_cond_wait 返回时,重新加锁 mutexmp = head;head = mp->next;pthread_mutex_unlock(&mutex);  //解锁 互斥量printf("---consumer id:---- %lu\\ :%d\\n", pthread_self(), mp->num);free(mp);sleep(rand()%3);}return NULL;
}int main(int argc, char *argv[])
{int ret;pthread_t pid, cid;srand(time(NULL));ret = pthread_create(&pid, NULL, producer, NULL); //生产者if(ret != 0){err_thread(ret, "pthread_create producer error");}pthread_create(&cid, NULL, consumer, NULL); //消费者if(ret != 0){err_thread(ret, "pthread_create consumer error");}pthread_create(&cid, NULL, consumer, NULL); //消费者if(ret != 0){err_thread(ret, "pthread_create consumer error");}pthread_create(&cid, NULL, consumer, NULL); //消费者if(ret != 0){err_thread(ret, "pthread_create consumer error");}pthread_join(pid, NULL); //回收线程pthread_join(cid, NULL);return 0;
}		

条件变量的优点

相较于mutex而言,条件变量可以减少竞争。

        如直接使用mutex,除了生产者、消费者之间要竞争互斥量以外,消费者之间也需要竞争互斥量,但如果汇聚(链表)中没有数据,消费者之间竞争互斥锁是无意义的。有了条件变量机制以后,只有生产者完成生产,才会引起消费者之间的竞争。提高了程序效率。

条件变量理解总结 

条件变量的作用 - 线程同步
手段: 条件变量控制的是线程的挂起与唤醒,所使用的主要相关函数是 “唤醒” 和 “等待”。

假如没有“条件变量”这个概念,如果一个线程要等待某个“自定义的条件”满足而继续执行,而这个条件只能由另一个线程来满足 

个人理解 

两个线程利用条件变量及互斥锁实现同步。条件变量和互斥锁对两个线程来说是全局的
一个线程利用条件变量实现等待,同时释放锁;
一个线程获取锁后利用该条件变量唤醒等待的线程。 

互斥锁+条件变量 

互斥锁主要用来共享资源上,而条件变量主要用来在满足条件时通知线程 

互斥锁就是保证线程间读写某个数值时的原子性,在执行操作时不会切换到其他线程,实现了原子操作(连续不间断),解决了一些资源竞争问题。  

  • 为什么条件变量经常要配合互斥量 mutex 一起合作?

        因为有时会有许多线程被唤醒,这些线程都会同时要求访问共享资源,因此需要 mutex 来保护共享资源。

1. 这是为了应对 线程1在调用pthread_cond_wait()但线程1还没有进入wait cond的状态的时候,此时线程2调用了 cond_singal 的情况。 如果不用mutex锁的话,这个cond_singal就丢失了。加了锁的情况是,线程2必须等到 mutex 被释放(也就是 pthread_cod_wait() 释放锁并进入wait_cond状态 ,此时线程2上锁) 的时候才能调用cond_singal。

2. 保证了只有一个线程基于条件变量阻塞

        简而言之就是,在thread 1 call pthread_cond_wait() 的时刻到 thread 1真正进入 wait 状态时,是存在着时间差的。如果在这段时间差内 thread2 调用了 pthread_cond_signal() 那这个 signal 信号就丢失了。给 wait 加锁可以防止同时有另一个线程在 signal