美文网首页
关于Golang的chan与go的位置的一点思考

关于Golang的chan与go的位置的一点思考

作者: flow__啊 | 来源:发表于2017-04-18 16:19 被阅读84次

上一段代码:

package main
import (
    "fmt"
)
func f1(in chan int) {
    fmt.Println(<-in)
}
func main() {
    out := make(chan int)
    out <- 2
    go f1(out)
}

这是不能编译的,提示说:
fatal error: all goroutines are asleep - deadlock!
有死锁,但是讲道理的话,是没有的。
如果我硬要让这段代码能编译通过呢?
改成如下代码;

func main() {
    out := make(chan int)
    go f1(out)
    out <- 2
}

讲道理,这和上一段没有什么实质的变化。那么问题来了,我再来一个go func,会产生死锁的那种,看看行还是不行。
代码如下:

func main() {
    out := make(chan int)
    go f1(out)
    out <- 2
    go f2(out)
    time.Sleep(1e9)
}

好吧,只要对chan后再进行go,就不会有什么问题了。

相关文章

网友评论

      本文标题:关于Golang的chan与go的位置的一点思考

      本文链接:https://www.haomeiwen.com/subject/apxqzttx.html