简体   繁体   English

带有 goroutine 的匿名函数

[英]Anonymous function with goroutines

I am trying to understand the difference between calling goroutine with/without anonymous function.我试图了解使用/不使用匿名函数调用 goroutine 之间的区别。 When I try below code with anonymous function it works.当我使用匿名函数尝试下面的代码时,它可以工作。

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)
}

Below code without a anonymous function fails with deadlock.下面没有匿名函数的代码因死锁而失败。

go fmt.Println(<-ch) //fatal error: all goroutines are asleep - deadlock!

The code is available here该代码可在此处获得

The Go Programming Language Specification Go 编程语言规范

Receive operator接收运算符

For an operand ch of channel type, the value of the receive operation <-ch is the value received from the channel ch.对于通道类型的操作数 ch,接收操作 <-ch 的值是从通道 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.表达式阻塞,直到值可用。


For example,例如,

package main

import "fmt"

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

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

Output:输出:

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

fmt.Println(<-ch) evaluates its arguments, a receive on ch . fmt.Println(<-ch)评估它的参数,在ch接收。 There is no send pending for ch . ch没有等待发送。 fmt.Println(<-ch) blocks until a value is available, which never happens, it never gets to ch <- 1 . fmt.Println(<-ch)阻塞直到一个值可用,这永远不会发生,它永远不会到达ch <- 1


It is equivalent to:它相当于:

package main

import "fmt"

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

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

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM