douba7784 2018-02-04 05:21
浏览 61
已采纳

goroutines死锁,需要一些解释

I wanted to understand how does the Go-routine work here.

Question 1: Does the go-routine inherit anything from the main GO routine/func??

Question 2: Also wanted to know if I send "hi whats up" into the msg channel why is it not received by the go-routine at LINE:13????

  1 package main
  2 
  3 import "fmt"
  4 
  5 func main() {
  6     msg := make(chan string, 2) //channel (bidirectional channel) of type string
  7 
  8     msg <- "hi whats up"
  9     fmt.Println("*****I am main go routine*****")
 10 
 11     go func() {
 12         fmt.Println("*****HI ABHI *****
")
 13         temp := <-msg
 14         fmt.Println(temp)
 15         msg <- "Hello from a goroutine!" //send a string through the channel
 16     }()
 17 
 18     fmt.Println("Main routine waiting for message")
 19 
 20     fmt.Println(<-msg) //receive the string from the channel
 21     fmt.Println(<-msg)
 22 }  

Getting following error:

*****I am main go routine*****

Main routine waiting for message

hi whats up

*****HI ABHI *****

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:

main.main()

/Users//work/go/src/github.com/Golang_play/goroutine/goroutine.go:21 +0x1e6

goroutine 5 [chan receive]:

main.main.func1(0xc420054060)

/Users/work/go/src/github.com/Golang_play/goroutine/goroutine.go:13 +0x98 created by main.main /Users/work/go/src/github.com/Golang_play/goroutine/goroutine.go:11 +0xe2 exit status 2

Also in the following program LINE 14 never prints.

 5 func main() {
  6     msg := make(chan string, 2) //channel (bidirectional channel) of type string
  7 
  8     msg <- "hi whats up"
  9     fmt.Println("*****I am main go routine*****")
 10 
 11     go func() {
 12         fmt.Println("*****HI ABHI *****
")
 13         temp := <-msg
 14         fmt.Println(temp)
 15         //msg <- "Hello from a goroutine!" //send a string through the channel
 16     }()
  • 写回答

3条回答 默认 最新

  • doulizhi1247 2018-02-04 05:36
    关注

    You're trying to send messages two ways on the same channel, and you don't do anything to guarantee who reads which messages. It's entirely possible for the main goroutine to receive the message it sent, before the func goroutine attempts to read from the channel. If that happens, both goroutines get stuck waiting for messages that will never arrive.

    Use two channels.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度