Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2375275
  • 博文数量: 298
  • 博客积分: 7876
  • 博客等级: 准将
  • 技术积分: 5500
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-23 13:39
文章存档

2013年(2)

2012年(142)

2011年(154)

分类: LINUX

2011-04-04 16:43:20

条件变量

定义:  pthread_cond_t

初始化:PTHREAD_COND_INITIALIZER    //只限于使用在静态分配条件变量

1pthread_cond_init()  但要调用 pthread_mutex_destroy 释放

 

#include

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

3int pthread_cond_destroy(pthread_cond_t *cond);

Both return: 0 if OK, error number on failure

 

等待条件为真:

#include

4int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);

5int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex,

const struct timespec *restrict timeout);

返回值:成功返回0, 否则返回错误编号

  第一个函数,先lock,接着等待条件,然后unlock

  第二个函数,多了时间限制,如果超过时限后条件还没发生,函数将再次请求mutex,并且然后ETIMEDOUT错误.

  时间限制使用下面这个结构体:

   struct timespec {

        time_t tv_sec;   /* seconds */

        long   tv_nsec;  /* nanoseconds */十亿分之一秒,毫微秒

     };

  时间限制是绝对值,所以要把相对时间转为绝对时间:

  void maketimeout(struct timespec *tsp, long minutes)

  {

     struct timeval now;

 

gettimeofday(&now);/*取得当前时间*/

     tsp->tv_sec = now.tv_sec;

     tsp->tv_nsec = now.tv_usec * 1000; /* usec to nsec */

tsp->tv_sec += minutes * 60;

   }

 

当条件满足时,使用下面两个函数之一来唤醒线程

#include

6int pthread_cond_signal(pthread_cond_t *cond);        //唤醒等待该条件的某个线程

7int pthread_cond_broadcast(pthread_cond_t *cond);     //唤醒等待该条件的所以线程

Both return: 0 if OK, error number on failure

 

********************************************************************

举例说明线程中的条件变量的使用

*********************************************************************

#include

#include

#include

 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t cond   = PTHREAD_COND_INITIALIZER;

int i=1;

 

void *thread1(void *junk)

{

    for(i=1;i<=9;i++)

    {

        pthread_mutex_lock(&mutex);

        if(i%3==0)

             pthread_cond_signal(&cond);

        else                

             printf("thead1:%d\n",i);

        pthread_mutex_unlock(&mutex);

        sleep(1);

    }

}

 

void *thread2(void *junk)

{

    while(i<=9)

    {

        pthread_mutex_lock(&mutex);

        if(i%3!=0)

            pthread_cond_wait(&cond,&mutex);

        printf("thread2:%d\n",i);

        pthread_mutex_unlock(&mutex);

        sleep(1);

    }

}

 

int main(void)

{

    pthread_t t_a;

    pthread_t t_b;

 

    pthread_create(&t_a,NULL,thread2,(void *)NULL);

    pthread_create(&t_b,NULL,thread1,(void *)NULL);

    pthread_join(t_b, NULL);

    pthread_mutex_destroy(&mutex);     

    pthread_cond_destroy(&cond);

    exit(0);

}

结果:

thead1:1

thead1:2

thread2:3

thead1:4

thead1:5

thread2:6

thead1:7

thead1:8

thread2:9

*********************************************************************

 

阅读(983) | 评论(0) | 转发(2) |
0

上一篇:(3)读写锁

下一篇:(7)线程同步

给主人留下些什么吧!~~