gpt4 book ai didi

选择 channel <- <- channel

转载 作者:IT王子 更新时间:2023-10-29 01:26:32 26 4
gpt4 key购买 nike

我很好奇为什么以下不起作用。一般selectdefault:防止死锁,但在这种情况下不是:

package main

import "fmt"

func main () {
a := make(chan int)
b := make(chan int)

select {
case a <- <- b:
fmt.Println("this is impossible")
default:
fmt.Println("select worked as naively expected")
}
}

显然它不喜欢 <- <-但我想知道这里的表面背后发生了什么。其他情况<- <-是允许的(尽管可能不推荐)。

最佳答案

a <- <- ba<- (<-b)相同,因为 <-运算符与最左边的 chan 关联可能。

所以 select有一个 case使用发送操作(以 a<- (something) 的形式)。这里发生的是发送语句的右侧表达式(要发送的值)首先被评估 - 这是 <-b .但这将永远阻塞(因为没有人在 b 上发送任何东西),所以:

fatal error: all goroutines are asleep - deadlock!

相关部分形成Spec: Select statements:

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

  1. For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.

  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. ...

所以如果default存在,select如果在第 2 步 中无法进行任何通信,但您的代码会卡在第 1 步 中,则确实会阻止阻塞。


只是为了完整,如果有一个 goroutine 会在 b 上发送一个值, 然后评估 <- b不会阻塞,所以执行 select不会卡在第 2 步,您会看到预期的 "select worked as naively expected" (因为从 a 接收仍然无法继续,因此将选择 default):

go func() { b <- 1 }()

select {
// ...
}

Go Playground 上试试.

关于选择 channel <- <- channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35615326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com