当工作完成时,goroutine是否会退出?

huangapple go评论82阅读模式
英文:

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 &quot;clean it up&quot;.

The Go runtime automatically &quot;reaps&quot; 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&#39;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>



huangapple
  • 本文由 发表于 2021年12月14日 01:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70338908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定