一个通道操作是否影响另一个通道操作

Is it one channel ops affect another channel ops

我做了这个简单的代码,想知道通道是如何工作的,不知何故如果通道c在通道b发送后发送,最后一个例程中的通道不会被发送,

我有 2 个通道,通道 c 用于将通道 b 拆分为切片的 4 个部分。

 package main

 import (
      "fmt"
      "strconv"
 )

 func runner(idx int, c chan []int, b chan []int) {
      var temp []int
      fmt.Println("runner " + strconv.Itoa(idx))
      bucket := <-b
      for k, v := range bucket {
           if v != 0 {
                temp = append(temp, v)
                bucket[k] = 0
           }
           if len(temp) == 5 {
                break
           }
      }

      //Strange condition if channel c is sent after channel b is sent,
      //somehow the last chan is not being sent
      b <- bucket
      c <- temp

      //this is right if channel b is sent after channel c is sent
    //c <- temp
    //b <- bucket

 }

 func printer(c chan []int) {
      for {
           select {
           case msg := <-c:
                fmt.Println(msg)
                //time.Sleep(time.Second * 1)
           }
      }
 }

 func main() {

      c := make(chan []int, 5)
      bucket := make(chan []int)

      go runner(1, c, bucket)
      go runner(2, c, bucket)
      go runner(3, c, bucket)
      go runner(4, c, bucket)

      bucket <- []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

      go printer(c)

      var input string
      fmt.Scanln(&input)

 }
  bucket := make(chan []int)

您的 b 通道的容量为 0。这意味着无论何时您向该通道发送内容,该通道都会立即变满,并且会阻塞直到接收者读取该通道。

当只剩下一个跑步者时,没有人会调用 bucket := <-b 来读取最后一个桶,因此最后一个 goroutine 永远停留在 b <- bucket 行,因此下一个最后一个 goroutine 永远不会调用第 c <- temp 行。