zoukankan      html  css  js  c++  java
  • golang之channel

    Buffered Channels

    package main
    
    import "fmt"
    
    func main() {
    	ch := make(chan int, 2)
    	ch <- 1
    	ch <- 2
    	fmt.Println(<-ch)
    	fmt.Println(<-ch)
    }

    如果操作一个空的channel会怎么样呢?

    package main
    
    import "fmt"
    
    func main() {
    	ch := make(chan int, 2)
    	ch <- 1
    	ch <- 2
    	fmt.Println(<-ch)
    	fmt.Println(<-ch)
    
    	v, ok := <-ch
    	fmt.Println(v,ok)
    }
    

    1
    2
    fatal error: all goroutines are asleep - deadlock!

    如果make函数不指定buffer length,会怎么样呢?

    func main() {
    	ch := make(chan int)
    	ch <- 1
    	fmt.Println(<-ch)
    }

    fatal error: all goroutines are asleep - deadlock!

    上述例子中sender,receiver都是同一个线程。

    如果sender,receiver是不同线程会怎么样呢?

    package main
    
    import "fmt"
    import "time"
    
    func WriteChannel(c chan int, v int) {
    	fmt.Printf("write %d to channel
    ", v)
    	c <- v
    }
    func main() {
    	c := make(chan int)
    	
    	go WriteChannel(c,1)
    	fmt.Println(<-c)
    	
    	time.Sleep(100 * time.Millisecond)
    	fmt.Printf("Done
    ")
    }

    运行又正常了。

  • 相关阅读:
    Python从文件中读取数据
    Python中类的继承
    Python中的类(2)
    Python中的类
    自动登陆抽屉(1)
    爬取汽车之家新闻
    Django简介
    web应用,http协议简介,web框架
    CentOS7安装python3.6
    MySQL之索引
  • 原文地址:https://www.cnblogs.com/gattaca/p/7998191.html
Copyright © 2011-2022 走看看