#include <pthread.h>
[注意]
互斥鎖是非異步安全,也就是說在信號處理中使用互斥鎖容易造成死鎖
[創建]
/*
* @brief 靜態創建並初始化條件變量
* @param[in] PTHREAD_COND_INITIALIZER 條件變量結構常量
*/
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
/*
* @brief 初始化條件變量
* @param[in|out] cond 條件變量
* @param[in] cond_attr 條件變量屬性
* @NULL 默認屬性
* @return 結果
* @li 0 成功
* @li !0 標準錯誤碼
*/
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr);
[等待]
/*
* @brief 等待條件變量
* @param[in|out] cond 條件變量
* @param[in] mutex 和條件變量一起使用的互斥鎖
* @return 結果
* @li 0 成功
* @li !0 標準錯誤碼
* @notes mutex主要用於多線程檢測條件變量的競爭處理
*/
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
[作業]
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t
*mutex, const struct timespec *abstime);
[激發]
/*
* @brief 激發一個線程
* @param[in|out] cond 條件變量
* @return 結果
* @li 0 成功
* @li !0 標準錯誤碼
*/
int pthread_cond_signal(pthread_cond_t *cond);
/*
* @brief 激發所有線程
* @param[in|out] cond 條件變量
* @return 結果
* @li 0 成功
* @li !0 標準錯誤碼
*/
int pthread_cond_broadcast(pthread_cond_t *cond);
[銷燬]
/*
* @brief 釋放條件變量佔用的所有資源
* @param[in|out] cond 條件變量
* @return 結果
* @li 0 成功
* @li !0 標準錯誤碼
* @notes 銷燬的時候,條件變量不能有線程處於等待狀態
*/
int pthread_cond_destroy(pthread_cond_t *cond);
pthread_cond_timedwait 函數出錯時返回下列錯誤代碼:
ETIMEDOUT abstime 指定的時間超時時,條件變量未觸發
EINTR pthread_cond_timedwait 被觸發中斷
pthread_cond_destroy 函數出錯時返回下列錯誤代碼:
EBUSY 某些線程正在等待該條件變量
例子:
#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
void *thread1(void *arg)
{
sleep(1);
while (1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("this is thread1!\n");
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thread2(void *arg)
{
sleep(1);
while (1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("this is thread2!\n");
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
int main(int argc, char **argv)
{
pthread_t id1, id2;
void *ret;
pthread_create(&id1, NULL, thread1, NULL);
pthread_create(&id2, NULL, thread2, NULL);
pthread_cond_init(&cond, NULL);
pthread_mutex_init(&mutex, NULL);
sleep(3);
while (1)
{
pthread_cond_signal(&cond);
printf("this is main!\n");
sleep(1);
}
pthread_join(id1, &ret);
pthread_join(id2, &ret);
return 0;
}