Home > database >  Does a goroutine exit when the work has completed
Does a goroutine exit when the work has completed

Time:12-14

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)
    } ()
}



 

CodePudding user response:

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

CodePudding user response:

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.

  • Related