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

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题