dongxie2613 2017-11-09 10:24
浏览 6
已采纳

如果任何通道关闭,是否有办法中断选择?

Let's say we are selecting on two channel. After running a few times, one of the channels is closed. How can I break out of the select?

package main

import (
    "fmt"
)

func main() {
    ch := make(chan int)
    closed := make(chan bool, 1)
    go func() {
        for i := 0; i < 5; i++ {
            ch <- 1
        }
        close(ch)
    }()

    for {
        select {
        case v := <-ch:
            fmt.Printf("v is %v
", v)
        case <-closed:
            fmt.Println("The server is closed!")
            return
        }
    }
    fmt.Println("Break!")
}

It is blocked infinitely. How to make it work?

  • 写回答

2条回答 默认 最新

  • dongsui0929 2017-11-09 10:35
    关注

    Here is working code that:

    1. Changed order of select-case. (according to the comment from @zzn this behavior is random and it's better not to rely on this - better to check if channel has been closed).
    2. Writes to the closed channel

    https://play.golang.org/p/K83XcPbr7b

    package main
    import (
        "fmt"
    )
    
    func main() {
        ch := make(chan int)
        closed := make(chan bool)
        go func() {
            for i := 0; i < 5; i++ {
                ch <- i
            }
            close(ch)
        closed <- true
        }()
    
        for {
            select {
            case <- closed:
                fmt.Println("The server is closed!")
                return
            case v := <- ch:
                fmt.Printf("v is %v
    ", v)
            }
        }
        fmt.Println("Break!")
    }
    

    If you don't change order of case there would be extra "zero" value: https://play.golang.org/p/JJaomKgqy8

    Maybe it's better to check if channel has been closed?

    https://play.golang.org/p/7Nd63b3JZ_

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        ch := make(chan int)
        go func() {
            for i := 0; i < 5; i++ {
                ch <- i
            }
            close(ch)
        }()
    
        for {
            select {
            case v, hasMore := <- ch:
            if !hasMore {
                return
            }
                fmt.Printf("v is %v
    ", v)
            }
        }
        fmt.Println("Break!")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line