gpt4 book ai didi

Golang channel 问题

转载 作者:行者123 更新时间:2023-12-01 22:31:31 24 4
gpt4 key购买 nike

我有一个简单的 channel 示例:https://play.golang.org/p/eLcpzXeCHms

package main

import (
"fmt"
)

func execute(trueChan chan<- bool, lowerRange int32, upperRange int32) {
for lowerRange <= upperRange {
fmt.Printf("\nhandling number %v", lowerRange)
if lowerRange%2 == 0 {
go func() {
trueChan <- true
}()
}
lowerRange++
}
close(trueChan)
}

func main() {
counter := 0

trueChan := make(chan bool)

execute(trueChan, 5, 25)

for {
if _, ok := <-trueChan; ok {
counter++
} else {
break
}
}

fmt.Printf("\n%v", counter)
}

第一个问题:我有时会收到一条错误消息...
handling number 5
handling number 6
handling number 7
handling number 8
handling number 9
handling number 10
handling number 11
handling number 12
handling number 13
handling number 14
handling number 15
handling number 16
handling number 17
handling number 18
handling number 19
handling number 20
handling number 21
handling number 22
handling number 23
handling number 24
handling number 25
0
panic: send on closed channel

第二个问题 - 我的计数器始终为 0。

有人可以给我一个提示,我做错了什么?

最佳答案

你的代码:

  • 创建无缓冲 channel trueChan .
  • 创建 10 个 goroutine,每个 goroutine 都会尝试写入 trueChan ,这将阻塞,直到从中读取某些内容。
  • 关闭trueChan ,然后返回 main()
  • main()打印 0因为它还没有从 goroutine 中读取任何内容
  • 同时,因为trueChan在步骤 3 中关闭,在 goroutine 完成使用它之前,第一个尝试写入 channel 的 goroutine 出现 panic

  • 至少,您不应该关闭 trueChan直到你知道所有的 goroutine 都用它完成了。实际上,您甚至在他们开始使用它之前就将其关闭。

    一个 sync.WaitGroup可能是做到这一点的一种方法,但在你的代码中如何做到这一点并不明显,因为我不完全确定你的目标。这段代码看起来像一个简单的练习,而不是一个真实的例子。如果你能解释你的目标,我可能会提供更具体的建议。

    关于Golang channel 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61138813/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com