美文网首页
golang 里 select 的奇怪特性 - 随机执行

golang 里 select 的奇怪特性 - 随机执行

作者: onecat_nil | 来源:发表于2021-02-24 17:30 被阅读0次

在 go 里面 select 会随机找一个...

golang github 上扒拉题图.jpg

官方文档地址

The Go Programming Language Specification

原文

Execution of a "select" statement proceeds in several steps:

  1. ...
  2. 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.
  3. ...

如果有一个或多个信道可执行,则通过统一的伪随机来选择其中一个。否则,如果存在默认情况,则选择该情况。如果没有默认情况,则 select 语句将阻塞,直到可以进行至少一种通信为止。

源码地址

golang/go

可以不看代码看注释,

先进行了随机选择,然后再按随机后的顺序尝试执行,成功就出循环

Example

func test() {
    c := make(chan int, 1)
    c2 := make(chan string, 1)
    c <- 1
    c2 <- "hello"
    if len(c) > 0 {

    }
    select {
    case v := <-c:
        fmt.Println("c:" + strconv.Itoa(v))
    case v := <-c2:
        fmt.Println("c2:" + v)
    default:
        fmt.Println("default")
    }
}

func main() {
    runtime.GOMAXPROCS(1)
    for {
        test()
    }
}

输入结果


output.png

相关文章

  • golang 里 select 的奇怪特性 - 随机执行

    在 go 里面 select 会随机找一个... 官方文档地址 The Go Programming Langua...

  • Golang并发模型:select进阶

    特性 nil的通道永远阻塞,即不执行。 break跳出for? select{}阻塞。 select应用场景 无阻...

  • select I/O多路复用

    select golang的并发模型和linux select类似golang提供了select关键字,实现I/O...

  • Go语言常用代码笔记(持续更新)

    ?循环读取Channel内容 ?golang 的 select 的功能和 select, poll, epoll ...

  • [MySQL]随机数

    获取[0, 1)的随机数 select rand() 获取[i, j)的随机数 select floor(i + ...

  • select 信道好帮手

    select 概念 select 应用场景 死锁 select 重要特性 select 概念 select 语句用...

  • golang select

    使用场景 监控事件 读取事件 写入事件 } PS:注意select语句如果做监听使用的话,尽量嵌套在for循环中,...

  • Go select

    通过select语句可以监听channel上的数据流动 Golang的select语句类似于UNIX的select...

  • select用法

    golang 的 select 的功能和select, poll, epoll相似, 就是监听 IO 操作,当 I...

  • Go concurrent

    并发是指在同一时间内可以执行多个任务,Golang通过编译器运行时,从语言级别上支持并发特性,因此Golang在语...

网友评论

      本文标题:golang 里 select 的奇怪特性 - 随机执行

      本文链接:https://www.haomeiwen.com/subject/fnisfltx.html