zoukankan      html  css  js  c++  java
  • linux条件变量

    条件变量用于线程之间的通信,和互斥锁一起使用。条件变量用于及时通知等待的线程条件的变化,使线程不至于错过变化。

    考虑下面的情况,有AB两个线程对index这个全局变量进行++,一个线程C用于判断,index是不是3的倍数,如果是就输出除以3的结果。

    根据时间片轮转的算法,线程应该是这样执行的。

    Index初值为1.

    A B C (此时index=3,输出)A B C(此时index=5,不输出) A(此时index=6,c还在队列的最后,错过)BC 。。。。

    我们能看出,C会每隔一段时间就错个一个。

    如图:

    因为三个线程的优先级一样,不存在抢占,而且CPU是把时间片分给每个线程的,所以C的错过是必然的。

    所以引入了条件变量。

    C线程调用pthread_cond_wait(cond,lock)函数来感知变化。

    代码:

    #include <pthread.h>  
    #include <semaphore.h>
    #include <unistd.h>  
    #include <stdio.h>
    #include<fcntl.h>
    #include <pthread.h>
    #include <errno.h>
    
    int index = 1;
    
    pthread_mutex_t lock;
    pthread_cond_t cond;
    
    void fun1(void){
    
        while(index<50){
            
        pthread_mutex_lock(&lock);    
        index++;
        printf("In fun1 : %d
    ",index);
        pthread_cond_signal(&cond);//当有变化后,使用signal通知wait函数
        pthread_mutex_unlock(&lock);
        usleep(0.1);
    
        }
    
    }
    
    void fun3(void){
    
        while(index<50){
            
        pthread_mutex_lock(&lock);    
        index++;
        printf("In fun1 : %d
    ",index);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&lock);
        usleep(0.1);
    
        }
    
    }
    
    void fun2(void){
    
        int i=0;
    
        while(i<70){
    
        pthread_mutex_lock(&lock);
    
        while(index%3!=0){
        
            pthread_cond_wait(&cond,&lock);//如果获得了互斥锁,但是条件不合适的话,wait会释放锁,不往下执行。当变化后,条件合适,将直接获得锁。
    
        }
        
    
        //if(index%3==0)    
        printf("%d
    ",index/3);
        //else
        //printf("no
    ");
        i++;
    
        pthread_mutex_unlock(&lock);
    
        usleep(0.1);
    
    
        }
    
    }
    
    int main(){
    
        pthread_mutex_init(&lock,NULL);
        pthread_cond_init(&cond,NULL);
    
        pthread_t tid1,tid2,tid3;
        pthread_create(&tid1,NULL,(void*)fun1,NULL);
        pthread_create(&tid2,NULL,(void*)fun2,NULL);
        pthread_create(&tid3,NULL,(void*)fun3,NULL);
    
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        pthread_join(tid3,NULL);
    
    
    
    
    }
  • 相关阅读:
    《构建之法》第四章 第十七章阅读笔记
    2016012037+小学四则运算练习软件项目报告
    阅读《构建之法》所得与初步思考
    随机产生300个四则运算题
    我与软件工程的相识,相知
    转 如何快速看懂一个大型程序 http://blog.csdn.net/jysg9/article/details/24193181
    SQL Server 存储过程(转)
    sql 视图的作用(转http://www.cup.edu.cn/nic/Programing/database/34943.htm)
    linux性能问题(CPU,内存,磁盘I/O,网络)( 转载)
    qtp测试计划
  • 原文地址:https://www.cnblogs.com/wzben/p/5431071.html
Copyright © 2011-2022 走看看