【问题标题】:Channel returns the same value twice on receive通道在接收时两次返回相同的值
【发布时间】:2021-04-23 06:06:03
【问题描述】:

您好,我有以下简单的程序:
我有一个函数printNums(nums chan int),它应该从一个通道中获取 3 个数字并同时打印它们。每次打印都在 range 语句内的新 goroutine 中完成。
然而,当我运行这个程序时,我得到的是12, 12, 32,而不是预期的输出4, 12, 32。你能帮我找出问题出在哪里,为什么我没有从频道收到与发送到频道相同的值吗?谢谢。

package main

import ("fmt")

func printNums(nums chan int){
    c := make(chan struct{}, 100)
        for num := range(nums){
            go func(){
                fmt.Println(num)
                c <- struct{}{}
            }()
        }
    <-c
    <-c
    <-c
}
func main(){
    nums := make(chan int)

  go func() {
      nums <- 4
      nums <- 12 
      nums <- 32 
      close(nums)
  }()

  printNums(nums)
}

【问题讨论】:

标签: go concurrency range channel goroutine


【解决方案1】:

您正在打印 num 的当前值,而不是创建 goroutine 时的值 num。循环变量每次都会被覆盖,goroutine 可能会看到更新的值。

for num := range(nums){
    go func(x int){
         fmt.Println(x)
         c <- struct{}{}
    }(num)
 }

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 2021-07-31
    • 1970-01-01
    • 2014-01-09
    • 2010-10-30
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    相关资源
    最近更新 更多