线程条件变量

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章