7.2 创建和销毁条件变量
方法
pthread_cond_init(condition, attr)
pthread_cond_destroy(condition)
pthread_condattr_init(attr)
pthread_condattr_destroy(attr)
用法
条件变量的类型为pthread_cond_t,必须在使用之前初始化。有如下两种方法来初始化条件变量:
- 声明时初始化,例如
pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;
- 使用pthread_cond_init()动态初始化
创建的条件变量的ID通过条件参数返回给调用该方法的线程(原句为The ID of the created condition variable is returned to the calling thread through the condition parameter);同时该方法允许设置条件变量的属性信息。
入参attr用于设置条件变量的属性,只有一个可设置的属性:是否允许进程间共享,如果开启则其他进程的线程也可以识别到该条件变量。attr的类型为pthread_condattr_t,该参数也可设为NULL,此时会使用默认值。注意不一定所有平台上都会提供允许进程间共享属性的具体实现。
pthread_condattr_init()和pthread_condattr_destroy()用于创建和销毁条件变量属性对象。当一个条件变量不再被使用时应该调用pthread_cond_destroy()来销毁它。