我编写了这个简单的代码,试图了解通道的工作方式,以某种方式,如果在发送通道b之后发送了通道c,没有发送最后一个例程中的通道,

我有2个通道,通道c用于将通道b拆分为 slice 的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

关于go - 是一个 channel 运营影响另一 channel 运营,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43152776/

10-12 23:37