【问题标题】:Closing channel of unknown length未知长度的封闭通道
【发布时间】:2016-03-20 21:23:28
【问题描述】:

如果不了解频道,我无法关闭频道
长度

package main

import (
    "fmt"
    "time"
)

func gen(ch chan int) {
    var i int
    for {
        time.Sleep(time.Millisecond * 10)
        ch <- i
        i++
        // when no more data (e.g. from db, or event stream)
        if i > 100 {
            break
        }
    }

    // hot to close it properly?
    close(ch)
}

func receiver(ch chan int) {
    for i := range ch {
        fmt.Println("received:", i)
    }
}

func main() {
    ch := make(chan int)

    for i := 0; i < 10; i++ {
        go gen(ch)
    }

    receiver(ch)
}

它给了我错误

panic: send on closed channel

goroutine 8 [running]:
main.gen(0xc82001a0c0)
    /home/exu/src/github.com/exu/go-workshops/100-concurrency-channels/16-close-problem.go:12 +0x57
created by main.main
    /home/exu/src/github.com/exu/go-workshops/100-concurrency-channels/16-close-problem.go:35 +0xbd

goroutine 1 [panicwait]:
runtime.gopark(0x0, 0x0, 0x50b8e0, 0x9, 0x10, 0x1)
    /usr/lib/go/src/runtime/proc.go:185 +0x163
runtime.main()
    /usr/lib/go/src/runtime/proc.go:121 +0x2f4
runtime.goexit()
    /usr/lib/go/src/runtime/asm_amd64.s:1696 +0x1

goroutine 6 [sleep]:
time.Sleep(0x989680)
    /usr/lib/go/src/runtime/time.go:59 +0xf9
main.gen(0xc82001a0c0)
    /home/exu/src/github.com/exu/go-workshops/100-concurrency-channels/16-close-problem.go:11 +0x29
created by main.main
    /home/exu/src/github.com/exu/go-workshops/100-concurrency-channels/16-close-problem.go:33 +0x79

goroutine 7 [sleep]:
time.Sleep(0x989680)
    /usr/lib/go/src/runtime/time.go:59 +0xf9
main.gen(0xc82001a0c0)
    /home/exu/src/github.com/exu/go-workshops/100-concurrency-channels/16-close-problem.go:11 +0x29
created by main.main
    /home/exu/src/github.com/exu/go-workshops/100-concurrency-channels/16-close-problem.go:34 +0x9b
exit status 2

这是合乎逻辑的 - 当第二个 goroutine 尝试发送给它时,第一个 goroutine 关闭通道。在这种情况下关闭渠道的最佳方法是什么?

【问题讨论】:

    标签: go concurrency channel


    【解决方案1】:

    一旦通道关闭,您就无法在其上发送更多值,否则它会出现恐慌。这就是你所经历的。

    这是因为你启动了多个使用相同通道的 goroutine,它们在通道上发送值。然后关闭每个通道中的通道。而且由于它们不同步,一旦第一个 goroutine 到达关闭它的点,其他人可能(并且他们将)仍然继续在其上发送值:恐慌!

    您只能关闭一次频道(尝试关闭已经关闭的频道也会出现恐慌)。当所有发送值的 goroutine 都完成后,你应该这样做。为此,您需要检测所有发送者 goroutine 何时完成。检测这种情况的惯用方法是使用sync.WaitGroup

    对于每个启动的发送者 goroutine,我们使用 WaitGroup.Add() 将 1 添加到 WaitGroup。每个完成发送值的 goroutine 都可以通过调用 WaitGroup.Done() 来发出信号。最好将此作为延迟语句执行,因此如果您的 goroutine 会突然终止(例如恐慌),WaitGroup.Done() 仍将被调用,并且不会让其他 goroutines 挂起(等待赦免 - “失踪”WaitGroup.Done() 调用那永远不会来……)。

    WaitGroup.Wait() 将等到所有发送者 goroutine 都完成后,并且只有在此之后才会关闭通道一次。我们想检测这个“全局”的 done 事件并关闭通道,同时处理发送的值,因此我们必须在它自己的 goroutine 中执行此操作。

    接收器 goroutine 将一直运行直到通道关闭,因为我们在通道上使用了 for ... range 构造。并且由于它在主 goroutine 中运行,因此在从通道正确接收和处理所有值之前,程序不会退出。 for ... range 构造循环,直到接收到在通道关闭之前发送的所有值。

    请注意,下面的解决方案也适用于缓冲和非缓冲通道,无需修改(尝试使用带有ch := make(chan int, 100) 的缓冲通道)。

    正确的解决方案(在Go Playground 上尝试):

    func gen(ch chan int, wg *sync.WaitGroup) {
        defer wg.Done()
        var i int
        for {
            time.Sleep(time.Millisecond * 10)
            ch <- i
            i++
            // when no more data (e.g. from db, or event stream)
            if i > 100 {
                break
            }
        }
    }
    
    func receiver(ch chan int) {
        for i := range ch {
            fmt.Println("received:", i)
        }
    }
    
    func main() {
        ch := make(chan int)
        wg := &sync.WaitGroup{}
    
        for i := 0; i < 10; i++ {
            wg.Add(1)
            go gen(ch, wg)
        }
    
        go func() {
            wg.Wait()
            close(ch)
        }()
    
        receiver(ch)
    }
    

    注意:

    请注意,receiver(ch) 在主 goroutine 中运行很重要,而代码等待 WaitGroup 并在其自己的(非主)goroutine 中关闭通道;而不是相反。如果您切换这 2 个,可能会导致“提前退出”,即并非所有值都可能从通道接收和处理。这是因为当主 goroutine 完成时 Go 程序退出(规范:Program execution)。它不会等待其他(非主)goroutine 完成。因此,如果等待和关闭通道将在主 goroutine 中,则在关闭通道后,程序可以随时退出,而不是等待在这种情况下会循环以从通道接收值的另一个 goroutine。

    【讨论】:

    • 感谢您的回答,我已根据您的想法实施了我的解决方案。
    【解决方案2】:

    "使用 Go 通道的一个一般原则是不要从接收方关闭通道,如果通道有多个并发发送方,也不要关闭通道。"

    一旦标记为清理,每个通道最终都会被 GC,因此可以不关闭通道,唯一的区别是该通道将在几个周期后可用于 gc明确关闭。

    不过,如果您可以关闭频道,那总是好的。请通过以下链接了解详细说明。

    文章 thisthis 展示了在 1:N、N:1 或 M:N(发送者:接收者)的情况下关闭通道的各种方法

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2014-10-05
      相关资源
      最近更新 更多