doukuangxun5382 2016-06-04 17:56
浏览 32
已采纳

选择默认频道竞争条件

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

Why does the default: in the select statement infinite loop the program?

package main

import (
    "fmt"
    "strconv"
    "time"
)

var quit chan bool
var counter chan int

func main() {
    counter = make(chan int)
    quit = make(chan bool)
    go func() {
        i := 0
        for {
            i++
            select {
            case <-quit:
                fmt.Println("Bye!")
                return
            case counter <- i:
                fmt.Println("Send! " + strconv.Itoa(i))
            default:
                fmt.Println("Default! " + strconv.Itoa(i))
            }
        }
    }()
    fmt.Println("Receive! " + strconv.Itoa(<-counter))
    fmt.Println("Receive! " + strconv.Itoa(<-counter))
    fmt.Println("Receive! " + strconv.Itoa(<-counter))
    fmt.Println("Receive! " + strconv.Itoa(<-counter))
    fmt.Println("Receive! " + strconv.Itoa(<-counter))
    fmt.Println("Receive! " + strconv.Itoa(<-counter))
    quit <- true
    time.Sleep(1 * time.Second)
}
  • 写回答

1条回答 默认 最新

  • douzong3599 2016-06-04 18:17
    关注

    When a select has a default, it becomes non-blocking. To quote the spec:

    If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

    Without the default, the select would wait until it could receive from quit or send on counter, do that, and then continue (going through the for loop again, unless it ran that return). With the default, the select never waits for anything and the default simply runs every time it can, unless one of the other operations goes through.

    In theory the program still works the same, and will exit after the sixth time of printing "Send!" and "Receive!" — but it might be too busy printing "Default!" several billion times to get there in a reasonable time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?