gpt4 book ai didi

go - goroutines的匿名函数

转载 作者:行者123 更新时间:2023-12-01 20:25:42 26 4
gpt4 key购买 nike

我试图理解使用/不使用匿名函数调用goroutine之间的区别。
当我尝试下面带有匿名功能的代码时,它可以工作。

package main

import (
"fmt"
"time"
)

func main() {
ch := make(chan int)

go func() {
fmt.Println(<-ch)
}()
go send(1, ch)

time.Sleep(100 * time.Millisecond)
}

下面没有匿名功能的代码将因死锁而失败。
go fmt.Println(<-ch) //fatal error: all goroutines are asleep - deadlock!

该代码可用 here

最佳答案

The Go Programming Language Specification

Receive operator

For an operand ch of channel type, the value of the receive operation <-ch is the value received from the channel ch. The channel direction must permit receive operations, and the type of the receive operation is the element type of the channel. The expression blocks until a value is available.



例如,
package main

import "fmt"

func main() {
ch := make(chan int)
go fmt.Println(<-ch)
ch <- 1
}

游乐场: https://play.golang.org/p/K3_V92NRWvY

输出:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
// At prog.go: line 7: (<-ch)
fmt.Println(<-ch)评估其参数,即对 ch的接收。 ch没有等待发送的消息。 fmt.Println(<-ch)阻塞,直到有一个值可用为止(永远不会发生),它永远不会到达 ch <- 1

它等效于:
package main

import "fmt"

func main() {
ch := make(chan int)
arg := <-ch
go fmt.Println(arg)
ch <- 1
}

游乐场: https://play.golang.org/p/1wyVTe-8tyB

输出:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
// At prog.go: line 7: arg := <-ch

关于go - goroutines的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573083/

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