条件变量的结构为pthread_cond_t,函数pthread_cond_init()被用来初始化一个条件变量。它的原型为:
extern int pthread_cond_init __P ((pthread_cond_t *__cond,__const pthread_condattr_t *__cond_attr));
其中cond是一个指向结构pthread_cond_t的指针,cond_attr是一个指向结构pthread_condattr_t的指 针。结构 pthread_condattr_t是条件变量的属性结构,和互斥锁一样我们可以用它来设置条件变量是进程内可用还是进程间可用,默认值是 PTHREAD_ PROCESS_PRIVATE,即此条件变量被同一进程内的各个线程使用。注意初始化条件变量只有未被使用时才能重新初始化或被释放。释放一个条件变量 的函数为pthread_cond_destroy(pthread_cond_t cond)。
也可以静态的初始化条件变量
pthread_cond_t my_condition = PTHREAD_COND_INITIALIZER;
函数pthread_cond_wait()使线程阻塞在一个条件变量上。它的函数原型为:
extern int pthread_cond_wait __P ((pthread_cond_t *__cond,pthread_mutex_t *__mutex));
调用这个函数时,线程解开mutex指向的锁并被条件变量cond阻塞。线程可以被函数pthread_cond_signal和函数 pthread_cond_broadcast唤醒线程被唤醒后,它将重新检查判断条件是否满足,如果还不满足,一般说来线程应该仍阻塞在这里,被等待被 下一次唤醒。这个过程一般用while语句实现。
通过下面的程序来理解:
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /*初始化互斥锁*/
- pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量
- void *thread1(void *);
- void *thread2(void *);
- int i=1;
- int main(void)
- {
- pthread_t t_a;
- pthread_t t_b;
- pthread_create(&t_a,NULL,thread1,(void *)NULL);/*创建进程t_a*/
- pthread_create(&t_b,NULL,thread2,(void *)NULL); /*创建进程t_b*/
- pthread_join(t_b, NULL);/*等待进程t_b结束*/
- pthread_mutex_destroy(&mutex);
- pthread_cond_destroy(&cond);
- exit(0);
- }
- void *thread1(void *junk)
- {
- for(i=1;i<=9;i++)
- {
- printf("IN one\n");
- pthread_mutex_lock(&mutex);//
- if(i%3==0)
- pthread_cond_signal(&cond);/*条件改变,发送信号,通知t_b进程*/
- else
- printf("thead1:%d\n",i);
- pthread_mutex_unlock(&mutex);//*解锁互斥量*/
- printf("Up Mutex\n");
- sleep(10);
- }
- }
- void *thread2(void *junk)
- {
- while(i<9)
- {
- printf("IN two \n");
- pthread_mutex_lock(&mutex);
- if(i%3!=0)
- pthread_cond_wait(&cond,&mutex);/*等待*/
- printf("thread2:%d\n",i);
- pthread_mutex_unlock(&mutex);
- printf("Down Mutex\n");
- sleep(10);
- }
- }
----------------------------
IN one
thead1:1
Up Mutex
IN two
IN one
thead1:2
Up Mutex
IN one
Up Mutex
thread2:3
Down Mutex
IN one
thead1:4
Up Mutex
IN two
IN one
thead1:5
Up Mutex
IN one
Up Mutex
thread2:6
Down Mutex
IN one
thead1:7
Up Mutex
IN two
IN one
thead1:8
Up Mutex
IN one
Up Mutex
thread2:9
Down Mutex
-------
总结
pthread_cond_wait()是在当点 unlock 等待常量,其他线程就可以得到锁了,当得到signal时候会又会lock,,,,,继续往当点走,直到unlock
阅读(6072) | 评论(0) | 转发(0) |