• go协程和管道小demo案例


    1.定义2个管道两个协程,一个协程写数据,一个协程读取数据。主线程。实施监控读取完成 代码如下

    package main
    
    import (
        "fmt"
    )
    func WriteData(wchan chan int){
        for i:=0; i<50;i++{
            wchan<-i;
            //time.Sleep(time.Second*2);
            fmt.Printf("wirte chan is %v
    ",i);
        }
        close(wchan);//关闭管道
    }
    
    func ReadData(wchan chan int, exichan chan bool){
        for {
            v,ok:= <-wchan;
            if !ok {
                break;
            }
            //time.Sleep(time.Second*2);//读管道
            fmt.Printf("read channle is %v
    ",v);
        }
        exichan <- true;
        close(exichan);
    }
    func main() {
        wchan:=make(chan int,50);
        exitchan:=make(chan bool,1);
        go WriteData(wchan);
        go ReadData(wchan,exitchan);
    
        for {//使用for循环阻塞
            bol,_:= <- exitchan;
            if bol {
                break;
            }
        }
        fmt.Printf("master process is end
    ");
    }

     2.使用3个协程完成sum求和问题

    package main
    
    import (
        "fmt"
    )
    
    func WChan(wchan chan int){
        for i:=0;i<2000;i++ {
            wchan <- i;
            //fmt.Printf("write data is %v
    ",i);
        }
        close(wchan);
    }
    func ReadChan(wchan chan int,signelChan chan bool,mapchan chan map[interface{}]interface{}){
        for {
            num,ok:= <- wchan;
            if !ok {
                break;
            }
            //fmt.Printf("read data is %v
    ",num);
    
            sum:=0;
            for j:=0;j<=num;j++ {
                sum=sum+j;
            }
            tmpMap:=make(map[interface{}]interface{});
            tmpMap[num]=sum;
            mapchan <- tmpMap;//写入map管道
    
            //fmt.Printf("num的数字为%vsum求和为%v
    ",num,sum);
        }
        signelChan <-true;
        close(signelChan);
    }
    
    func reeadMap(mapChan chan map[interface{}]interface{}){
        for {
            tmpMap,ok:= <-mapChan;
            if !ok {
                break;
            }
            for k,v:=range tmpMap {
                fmt.Printf("key=%v value=%v
    ",k,v);
            }
        }
    }
    
    
    func main(){
        writechan:=make(chan int ,2000);//写管道
        bolChan:=make(chan bool);//信号量管道
        mapchan:=make(chan map[interface{}]interface{});
        go WChan(writechan);
        go ReadChan(writechan,bolChan,mapchan);
        go reeadMap(mapchan);
        for {
            bol,_:= <-bolChan;
            if !bol {
                break;
            }
        }
    }
  • 相关阅读:
    默认值设置
    关于设置 存储 内部存储空间只显示图片不显示视频的解决方法
    sd卡的监听
    android 设置时间12/24小时制
    详解BMP木马
    C#中类和接口的设计思想(本人认为比较好的思想,欢迎大家讨论指点)
    从XML中读取数据到内存的实例
    如何在代码中通过命令行创建SQL SERVER 数据库
    Visual Studio 2005 新特性 之 可空类型
    install shield11.5 如何制作卸载程序
  • 原文地址:https://www.cnblogs.com/zh718594493/p/14161316.html
Copyright © 2020-2023  润新知