条件变量函数
操作 |
相关函数说明 |
---|---|
初始化条件变量 |
pthread_cond_init 语法 |
基于条件变量阻塞 |
pthread_cond_wait 语法 |
解除阻塞特定线程 |
pthread_cond_signal 语法 |
在指定的时间之前阻塞 |
pthread_cond_timedwait 语法 |
在指定的时间间隔内阻塞 |
pthread_cond_reltimedwait_np 语法 |
解除阻塞所有线程 |
pthread_cond_broadcast 语法 |
销毁条件变量状态 |
pthread_cond_destroy 语法 |
初始化条件变量
使用 pthread_cond_init(3C) 可以将 cv 所指示的条件变量初始化为其缺省值,或者指定已经使用 pthread_condattr_init() 设置的条件变量属性。
pthread_cond_init 语法
int pthread_cond_init(pthread_cond_t *cv, const pthread_condattr_t *cattr);
#include pthread_cond_t cv; pthread_condattr_t cattr; int ret; ret = pthread_cond_init(&cv, NULL); ret = pthread_cond_init(&cv, &cattr);
cattr 设置为 NULL。将 cattr 设置为 NULL 与传递缺省条件变量属性对象的地址等效,但是没有内存开销。对于 Solaris 线程,请参见cond_init 语法。
使用 PTHREAD_COND_INITIALIZER 宏可以将以静态方式定义的条件变量初始化为其缺省属性。PTHREAD_COND_INITIALIZER 宏与动态分配具有 null 属性的pthread_cond_init() 等效,但是不进行错误检查。
多个线程决不能同时初始化或重新初始化同一个条件变量。如果要重新初始化或销毁某个条件变量,则应用程序必须确保该条件变量未被使用。
pthread_cond_init 返回值
pthread_cond_init() 在成功完成之后会返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,该函数将失败并返回对应的值。
EINVAL
描述:
cattr 指定的值无效。
EBUSY
描述:
条件变量处于使用状态。
EAGAIN
描述:
必要的资源不可用。
ENOMEM
描述:
内存不足,无法初始化条件变量。
基于条件变量阻塞
使用 pthread_cond_wait(3C) 可以以原子方式释放mp 所指向的互斥锁,并导致调用线程基于 cv 所指向的条件变量阻塞。对于 Solaris 线程,请参见cond_wait 语法。
pthread_cond_wait 语法
int pthread_cond_wait(pthread_cond_t *cv,pthread_mutex_t *mutex);
#include pthread_cond_t cv; pthread_mutex_t mp; int ret; ret = pthread_cond_wait(&cv, &mp);