小编use*_*557的帖子

为什么调用goroutine的顺序和方式很重要?

我正在尝试了解goroutine。在下面的示例中,为什么1)-4)表现不同?参见https://play.golang.org/p/_XXZe47W53v

package main
import (
  "fmt"
  "time"
)

func send(x int, ch chan int) {ch<-x}
func read(ch chan int) {fmt.Println(<-ch)}

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

    go read(ch)              // 1) works
    go send(1,ch)            // -> 1

    // go fmt.Println(<-ch)  // 2) fatal error: all goroutines are asleep - deadlock!
    // go send(1,ch)         // isn't this the same as the above ?

    // go send(1,ch)         // 3) works
    // go fmt.Println(<-ch)  // -> 1

    // go fmt.Println(<-ch)  // 4) …
Run Code Online (Sandbox Code Playgroud)

go goroutine

-1
推荐指数
1
解决办法
47
查看次数

标签 统计

go ×1

goroutine ×1