zoukankan      html  css  js  c++  java
  • Linux线程同步(4): 条件变量

    转自:http://blog.csdn.net/dai_weitao/archive/2007/08/22/1754964.aspx 

    条件变量分为两部分: 条件和变量. 条件本身是由互斥量保护的. 线程在改变条件状态前先要锁住互斥量. 

    1. 初始化:

        条件变量采用的数据类型是pthread_cond_t, 在使用之前必须要进行初始化, 这包括两种方式:

    • 静态: 可以把常量PTHREAD_COND_INITIALIZER给静态分配的条件变量.
    • 动态: pthread_cond_init函数, 是释放动态条件变量的内存空间之前, 要用pthread_cond_destroy对其进行清理.
    #include <pthread.h>

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

    成功则返回0, 出错则返回错误编号.

        当pthread_cond_init的attr参数为NULL时, 会创建一个默认属性的条件变量; 非默认情况以后讨论.

    2. 等待条件:

    #include <pthread.h>

    int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restric mutex);
    int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict timeout);

    成功则返回0, 出错则返回错误编号.

        这两个函数分别是阻塞等待和超时等待.

        等待条件函数等待条件变为真, 传递给pthread_cond_wait的互斥量对条件进行保护, 调用者把锁住的互斥量传递给函数. 函数把调用线程放到等待条件的线程列表上, 然后对互斥量解锁, 这两个操作是原子的. 这样便关闭了条件检查和线程进入休眠状态等待条件改变这两个操作之间的时间通道, 这样线程就不会错过条件的任何变化.

        当pthread_cond_wait返回时, 互斥量再次被锁住.

    3. 通知条件:

    #include <pthread.h>

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

    成功则返回0, 出错则返回错误编号.

        这两个函数用于通知线程条件已经满足. 调用这两个函数, 也称向线程或条件发送信号. 必须注意, 一定要在改变条件状态以后再给线程发送信号.

  • 相关阅读:
    (转)DMA(Direct Memory Access)
    linux根文件系统的挂载过程详解
    Linux根文件系统的挂载过程详解
    1byte、1KB、4KB,1MB、1GB用16进制表示的范围。任意地址范围求字节数
    Hi3531a海思logo加载的实现流程
    u-boot中添加mtdparts支持以及Linux的分区设置
    在uboot里面添加环境变量使用run来执行
    (转) 嵌入式 Linux 利用 udev 实现自动检测挂载U盘
    Shell之变量
    Shell之哈希表
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2034016.html
Copyright © 2011-2022 走看看