英文:
Does a goroutine exit when the work has completed
问题
我有一个Go程序,它是一个服务,不会在发生崩溃或主动关闭之前退出。
在这个程序中,我订阅了一个消息队列。订阅方法运行了一系列我希望并发运行的事件。我不需要等待它们完成。
这些goroutine并不总是使用通道,有时它们只是我想要并发运行的执行块。下面是一个示例- goroutine 调用了两次 fmt.Printf()。在这两次调用之后,它会完成并由垃圾回收器清理,还是我需要显式关闭它?
messageQueue.Subscribe("topic/print", topicPrint)
func topicPrint() {
go func() {
fmt.Println("这是一些主题信息")
fmt.Println(topic.Title, topic.Body)
}()
}
英文:
I have a go program that is a service and is not expected to exit until there is a crash or a deliberate shutdown.
In this program I subscribe to a message queue. The subscribing method runs a series of event that I wish to run concurrently. I have no need to wait until they are complete.
These goroutine does not always use channels, sometime it is just a block of execution that I want to run concurrently. Example below - the goroutine calls fmt.Printf() twice. After those two calls, does it complete and get cleaned up by the GC, or do I need to explicitly close it?
messageQueue.Subscribe("topic/print", topicPrint)
func topicPrint() {
go func () {
fmt.Println("Here is some topic information")
fmt.Println(topic.Title, topic.Body)
} ()
}
</details>
# 答案1
**得分**: 3
在你的例子中,像你所示的那样,流出goroutine的末尾是正确的结束方式。没有必要显式地“清理它”。
Go运行时会自动“回收”已完成的goroutine,尽可能地重用资源(实际发生的情况是实现细节,可能会发生变化)。
<details>
<summary>英文:</summary>
Flowing off the end of a goroutine like in your example is the correct way to end it. There is no need to explicitly "clean it up".
The Go runtime automatically "reaps" finished goroutines, reusing resources as much as possible (what *actually* happens is implementation detail and subject to change).
</details>
# 答案2
**得分**: 2
Go协程类似于执行线程,它们执行代码,完成后由垃圾回收器清理。
如果你需要长时间运行的协程(类似于线程),你需要告诉它。你可以使用通道与协程进行通信,使用`for`循环和`select`语句。
请查看https://gobyexample.com/goroutines以获取具体示例。
请注意,如果你告诉协程不要退出,你也*需要*告诉它何时退出。例如,可以通过关闭通道来实现。
<details>
<summary>英文:</summary>
Go routines are like execution threads, they execute the code and when they're done are cleaned up by the GC.
If you need long-living goroutines (think threads), you need to tell it. You can use channels to communicate with your goroutine; Using `for` loop and `select` statements.
Check out https://gobyexample.com/goroutines for concrete examples.
Note that if you tell it not to exit, you also *need* to tell it when to exit. This can be done by closing a channel for example.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论