当前位置:   article > 正文

golang chan_go 判断 chan没有数据了

go 判断 chan没有数据了


 

  1. package main
  2. import "fmt"
  3. func main() {
  4. c := make(chan int, 1)
  5. select {
  6. case c <- 10 : // 写入chan
  7. }
  8. select {
  9. case c <- 20 : // 写入chan,写不进去就丢弃
  10. default:
  11. }
  12. value , ok := <- c // 从chan中读取,ok是用来判断通道c是否关闭,
  13. // 如果通道c关闭,仍然有数据,则ok为true,直到没有数据ok为false
  14. fmt.Printf("value(%T)(%v) = %v\n",value, ok, value)
  15. close(c)
  16. value , ok = <- c // 从chan中读取
  17. fmt.Printf("value(%T)(%v) = %v\n",value, ok, value)
  18. }

value(int)(true) = 10
value(int)(false) = 0


带缓存chan

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func send(p chan<- int) {
  7. for i := 0; i < 5; i++ {
  8. p <- i
  9. fmt.Println("send:", i)
  10. }
  11. }
  12. func receive(c <-chan int) {
  13. for i := 0; i < 5; i++ {
  14. v := <-c
  15. fmt.Println("receive:", v)
  16. }
  17. }
  18. func main() {
  19. ch := make(chan int,5)
  20. go send(ch)
  21. go receive(ch)
  22. time.Sleep(1 * time.Second)
  23. }

send: 0
send: 1
send: 2
send: 3
send: 4
receive: 0
receive: 1
receive: 2
receive: 3
receive: 4


不带缓存chan
 

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func send(p chan<- int) {
  7. for i := 0; i < 5; i++ {
  8. p <- i
  9. fmt.Println("send:", i)
  10. }
  11. }
  12. func receive(c <-chan int) {
  13. for i := 0; i < 5; i++ {
  14. v := <-c
  15. fmt.Println("receive:", v)
  16. }
  17. }
  18. func main() {
  19. ch := make(chan int)
  20. go send(ch)
  21. go receive(ch)
  22. time.Sleep(1 * time.Second)
  23. }

receive: 0
send: 0
send: 1
receive: 1
receive: 2
send: 2
send: 3
receive: 3
receive: 4
send: 4

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func send(p chan<- int) {
  7. for i := 0; i < 3; i++ {
  8. p <- i
  9. fmt.Println("send:", i)
  10. }
  11. }
  12. func receive(p <- chan int){
  13. for{
  14. select{
  15. case <-p:
  16. fmt.Println("hello world")
  17. }
  18. }
  19. }
  20. func main() {
  21. ch := make(chan int)
  22. go send(ch)
  23. go receive(ch)
  24. time.Sleep(1 * time.Second)
  25. }

send: 0
hello world
hello world
send: 1
send: 2
hello world

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/549129
推荐阅读
相关标签
  

闽ICP备14008679号