Checking channel length becomes unresponsive in `for{ len(c) }`

纵饮孤独 提交于 2019-12-13 11:22:56

问题


The following program never prints "Full". With fmt.Println(len(choke)) uncommented, the program outputs "Full" when the channel is full.

package main

import (
    "fmt"
)

func main() {
    choke := make(chan string, 150000)

    go func() {
        for i := 0; i < 10000000; i++ {
            choke <- string(i)
            fmt.Println("i=", i)
        }
    }()

    for {
        //fmt.Println(len(choke))
        if len(choke) >= 150000 {
            fmt.Println("Full")
        }
    }
}

@tim-heckman explained the cause of this behavior in OP.

How do I detect a channel is full without using a hot loop?


回答1:


Use a select statement on the write side. It will write to the channel if there is buffer available or a receiver waiting; it will fallthrough to the default case if the channel is full.

func main() {
    choke := make(chan string, 150000)
    var i int
    for {
        select {
        case choke <- string(i):
            i++
        default:
            fmt.Println("Full")
            return
        }
    }
}


来源:https://stackoverflow.com/questions/48939522/checking-channel-length-becomes-unresponsive-in-for-lenc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!