sách gpt4 ăn đã đi

选择 channel <- <- channel

In lại 作者:IT王子 更新时间:2023-10-29 01:26:32 27 4
mua khóa gpt4 giày nike

我很好奇为什么以下不起作用。一般lựa chọnsử dụngmặc định:防止死锁,但在这种情况下不是:

gói chính

nhập khẩu "fmt"

hàm main () {
a := make(chan int)
b := make(chan int)

lựa chọn {
case a <- <- b:
fmt.Println("this is impossible")
mặc định:
fmt.Println("select worked as naively expected")
}
}

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

câu trả lời hay nhất

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

Vì thế lựa chọn有一个 trường hợp使用发送操作(以 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. ...

所以如果mặc định存在,lựa chọn如果在Bước 2 中无法进行任何通信,但您的代码会卡在Bước 1 中,则确实会阻止阻塞。


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

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

lựa chọn {
// ...
}

hiện hữu Đi đến Sân chơi 上试试.

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

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress