Golang 频道问题

我有一个简单的频道示例: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。


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


有只小跳蛙
浏览 107回答 2
2回答

米琪卡哇伊

你的代码:创建一个无缓冲的通道trueChan。创建 10 个 goroutine,每个 goroutine 都将尝试写入trueChan,这将阻塞直到有东西从中读取。关闭trueChan,然后返回main()main()打印0,因为它还没有从 goroutine 中读取任何内容同时,由于trueChan在步骤 3 中关闭,在 goroutine 完成使用它之前,第一个尝试写入通道的 goroutine 出现恐慌至少,在trueChan您知道所有 goroutine 都已完成之前,您不应该关闭它。实际上,您甚至在他们开始使用它之前就将其关闭。Async.WaitGroup可能是做到这一点的一种方法,但在你的代码中如何做到这一点并不明显,因为我不完全确定你的目标。这段代码看起来像一个简单的练习,而不是一个真实的例子。如果你能解释你的目标,我可能会提供更具体的建议。

慕虎7371278

您的第一个和第二个问题在同一个根源:您在主程序中关闭通道,程序关闭通道,在您的例程将数据发送到通道之前退出程序您通常必须在使用该程序的延迟中关闭通道香奈儿。例如,对于 yout 代码的修复:package mainimport (&nbsp; &nbsp; "fmt")func execute(trueChan chan<- bool, lowerRange int32, upperRange int32) {&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; defer func(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; close (trueChan)&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; &nbsp; &nbsp; for lowerRange <= upperRange {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("\n handling number %v", lowerRange)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if lowerRange%2 == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; trueChan <- true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lowerRange++&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()}func main() {&nbsp; &nbsp; counter := 0&nbsp; &nbsp; trueChan := make(chan bool)&nbsp; &nbsp; execute(trueChan, 5, 25)&nbsp; &nbsp; for _ = range trueChan{ // For small improvement here. Ref as below&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("\n%v", counter)}https://tour.golang.org/concurrency/4
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go