packagemainimport("fmt")funcf1(inchanint){fmt.Println(
3 回答
ThomasHuke
TA贡献5条经验 获得超2个赞
package main import ( "fmt" "time" ) func f1(in chan int) { fmt.Println(<-in) } func main() { out := make(chan int) go func() { out <- 2 }() f1(out) time.Sleep(time.Second) } //或者: package main import ( "fmt" "time" ) func f1(in chan int) { fmt.Println(<-in) } func main() { out := make(chan int,2) out <- 2 go f1(out) time.Sleep(time.Second) }
哔哔one
TA贡献1854条经验 获得超8个赞
改成这样:packagemainimport("fmt")funcf1(inchanint){fmt.Println(<-in)}funcmain(){out:=make(chanint)gof1(out)out<-2}因为你make是不带缓冲的chan所以chan需要有人消费才能写入,不然会阻塞因此还有第二种方法,生成带缓冲的chan:make(chanint,1)
Qyouu
TA贡献1786条经验 获得超11个赞
out队列无缓冲,主线程会阻塞在这里。解决方法有两个。第一,设置缓冲:packagemainimport("fmt")funcf1(inchanint){fmt.Println(<-in)}funcmain(){out:=make(chanint,1)out<-2gof1(out)}第二,将gof1(out)提前:packagemainimport("fmt")funcf1(inchanint){fmt.Println(<-in)}funcmain(){out:=make(chanint)gof1(out)out<-2}
添加回答
举报
0/150
提交
取消