zoukankan      html  css  js  c++  java
  • on the go way (二)channel 的用法

    在Go语言中channel的使用方法有很多,首先来看以下的使用方法

    1)当作事件信号来用,当某一件事完成之后,通知另一件事的完成

        

    package main
    
    import "fmt"
    
    func onedream(exit chan int){
    for i:=0;i<10;i++{
    fmt.Println("hello ",i)
    }
    exit<-0
    
    }
    func main(){
    var wait =make(chan int)
    go onedream(wait)
    
    <-wait
    fmt.Println("this goroutine over") 
    close(wait) }
     1 package main
     2 import 
     3 (
     4  "fmt"
     5  "time"   
     6 )
     7 func onedream(start ,wait chan int ){
     8     fmt.Println("等待制造数据命令中....")
     9     <-start
    10     fmt.Println("开始制造数据-----")
    11     for i:=0;i<10;i++{
    12         fmt.Println("hello world ",i)
    13     }
    14     wait<-0
    15 }
    16 func main(){
    17     var start1=make(chan int)
    18     var wait1=make(chan int)
    19     go onedream(start1,wait1)
    20     time.Sleep(time.Second*10)
    21     fmt.Println("发命令开始造数据")
    22     start1<-1
    23     <-wait1
    24     
    25     fmt.Println("制造数据结束....")
    26     close(start1)
    27     close(wait1)
    28 }

    2)多个线程同时进行

     1 package main 
     2 import(
     3     "fmt"
     4 )
     5 func onedream(index int,exit chan int){
     6     fmt.Println("this is  my index ",index)
     7     exit<-index
     8 }
     9 func main(){
    10     var flag=make(chan int ,10)
    11     for i:=0;i<10;i++{
    12        go onedream(i,flag)
    13     }
    14     
    15     for i:=0;i<10;i++{
    16         fmt.Println("back index is ",<-flag)
    17     }
    18     
    19     close(flag)
    20     
    21 }
  • 相关阅读:
    iOS单选和全选
    仿微信-ActionSheet
    NSArray 快速求和、平均值、最大值、最小值
    iOS学习资源集合
    iOS-Runtime字体适配
    仿网易新闻标题栏
    极光推送封装
    iOS导航栏自由缩放头像效果
    iOS判断字母、数字串
    Perl6多线程3: Promise start / in / await
  • 原文地址:https://www.cnblogs.com/OneDream/p/5306227.html
Copyright © 2011-2022 走看看