POSIX多线程程序设计学习篇之三(条件变量)

1,创建和销毁条件变量
 int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr);

 cond_attr 默认值是PTHREAD_ PROCESS_PRIVATE;

 pthread_cond_ destroy(pthread_cond_t *cond);


 条件变量必须声明为pthread_cond_t类型,必须在使用前初始化。有两种方式可以初始条件变量:
(1)静态声明:
pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;  

(2)动态声明:
用pthread_cond_init()函数动态地。创建的条件变量ID通过condition参数返回给调用线程。该方式允许设置条件变量对象的属性,attr。

2,等待和发送信号
extern int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex);
extern int pthread_cond_timedwait (pthread_cond_t  *cond,pthread_mutex_t  *mutex,const struct timespec *abstime);  //有等待的时间限制
extern int pthread_cond_signal(pthread_cond_t *cond);//唤醒满足条件的其中一个。
extern int pthread_cond_broadcast(pthread_cond_t *cond);//唤醒所有满足条件的。

(1)wait:
函数用于等待条件被触发。
a, 互斥量对该条件进行保护,传入的互斥量必须是已经锁住的。
b, 当不满足条件是,它会解锁互斥量。
c,当等待条件满足时又会锁定互斥量。


(2)timewait:
函数要求传入的时间值是一个绝对值,不是相对值,即比如起始时间是1,要等待10,则要填11。


(3)signal:
向等待条件的线程发送唤醒信号。
pthread_cond_signal()函数只会唤醒等待该条件的某个线程。
pthread_cond_broadcast()会广播条件状态的改变,以唤醒等待该条件的所有线程。(多个线程对共享资源只读,可以将它们全部唤醒)

以下是一个简单的例子可供参考

    #include <stdio.h>    
    #include <stdlib.h>    
    #include <pthread.h>    
    #define MAX  (10) 
    pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;    
    pthread_cond_t cond=PTHREAD_COND_INITIALIZER;    
        
    void* cond1();    
    void* cond2();    
        
    int count=0;    
   
    void* cond1()    
    {    
        while(1)    
        {    
            pthread_mutex_lock(&mutex);    
            pthread_cond_wait(&cond,&mutex);    
            printf("cond1 Count =  %d\n",++count);    
            pthread_mutex_unlock(&mutex);  
            if(count>=MAX) return ;    
        }    
    }    
        
    void* cond2()    
    {    
        while(1)   
        {    
            pthread_mutex_lock(&mutex);    
            if(count < MAX/2)    
            {    
               pthread_cond_signal(&cond);    
            }    
            else    
            {     
                printf("cond2 Count =  %d\n",++count);     
            }    
            pthread_mutex_unlock(&mutex);    
            if(count >= MAX)
	    {
                pthread_cond_signal(&cond); 
                return ;  
	    }     
        }    
    }    

    int main()    
    {       
        pthread_t thread1,thread2;    
        pthread_create(&thread2,NULL,cond1,NULL);    
        pthread_create(&thread1,NULL,cond2,NULL);    
            
        pthread_join(thread1,NULL);    
        pthread_join(thread2,NULL);    
           
        printf("count: %d\n",count);    
        return 0;    
    } 
















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值