return problems when traversing channel golang

Today I joined when traversing the channel data in a business code, business code, there are return, but after a return to traverse stopped, for example:

package main
import (
   "fmt"
   "sync"
   "time"
)
func consumer(cname string, ch chan int) {
   //可以循环 for i := range ch 来不断从 channel 接收值,直到它被关闭。
   for i := range ch {
      time.Sleep(1*time.Second)
      if i>20{
         return
      }
      fmt.Println("consumer-----------", cname, ":", i)
   }
   fmt.Println("ch closed.")
}

func producer(pname string, ch chan int) {
   for i := 0; i < 1000; i++ {
      //time.Sleep(1*time.Second)
      fmt.Println("producer--", pname, ":", i)
      ch <- i
   }
}


func main() {
   //用channel来传递"产品", 不再需要自己去加锁维护一个全局的阻塞队列
   ch := make(chan int,500)
   go producer("生产者", ch)
   for i:=0;i<5;i++  {
     go consumer("消费者", ch)
   }
   time.Sleep(1000 * time.Second)
   close(ch)
   time.Sleep(10 * time.Second)
}

Once i is greater than 20, consumption data from the pipe continuously stopped, so when traversing the channel not to put the best business code, put a return is totally unacceptable, of course, panic is also not allowed.

Published 169 original articles · won praise 224 · views 260 000 +

Guess you like

Origin blog.csdn.net/sureSand/article/details/86495706