dtttlua7165 2014-06-26 08:38
浏览 148
已采纳

为什么我的goroutine不执行? [重复]

This question already has an answer here:

I'm learning Go and I wanted to try goroutines and channels.

Here's my code:

package main
import "fmt"
func main(){

messages := make(chan string,3)

messages <- "one"
messages <- "two"
messages <- "three"

go func(m *chan string) {
    fmt.Println("Entering the goroutine...")
    for {
        fmt.Println(<- *m)
    }
}(&messages)

fmt.Println("Done!")
}

And here's the result:

Done!

I don't understand why my goroutine is never executed. The "Entering the goroutine" is not printed and I don't have any error message.

</div>
  • 写回答

2条回答 默认 最新

  • dongpian4954 2014-06-26 08:47
    关注

    The fact is that your goroutine starts, but is ended before doing anything because your program stop right after printing Done!: execution of goroutines is independant of the main program, but will be stopped at the same than the program. So basically, you need some process to make the program wait for them. It could be another channel waiting for a number of messages, a sync.WaitGroup, or other tricks.

    You should read the excellent post about concurrency in go in the golang blog.

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

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?