Instantiate goroutine in Function

I have a requirement where it would be easier to write a goroutine in a function (IE it is not created as part of the main function. Will the goroutine continue to run as expected once the function exits, and is this considered good practice? To date the only examples I have seen show goroutines being instantiated in the main thread/routine only, and I am not sure whether this is because it is mandated to do so, or purely for the sake of example brevity.

An apparently working example to demonstrate:

package main

import (

func printForever() { // Our goroutine
	x := 0
	for {
		fmt.Printf("hello again # %v\n", x)
		time.Sleep(1 * time.Second)

func doSomething() {
	go printForever()
	fmt.Println("all done here")

func main() {
	doSomething() // Call my routine
	for {
	} // stay here for ever
1 Like

Why you’re starting new goroutines, or what you’re doing in those goroutines may or may not be considered good practice, but there’s nothing wrong or irregular about starting goroutines from functions other than main; it’s completely normal.

thanks @skillian, you were too quick on the draw, hehe. I just uploaded a working example that I quickly through together. It executes just fine, but I wasn’t sure whether this idiomatic style of code is frowned upon in Go. I think you’ve answered my question, thanks.

and just to clarify, it is ok to leave a goroutine running concurrently, even when the called function that instantiated it has since exited. Correct? That is how my example programming is working, and so far so good…

It’s OK to leave a goroutine running after the function that created it returns. The goroutine doesn’t have any link to the function that instantiated it or vice versa.

I suspect you have a for {} loop that does nothing there in main just to make sure that your goroutine doesn’t get stopped before it gets the chance to run. I will say that as your program is right now, your printForever program really will run for the whole program. There are situations where you really do want that, and there are some where you want it to run in the background, independent of the function that started it, but still want to be able to cancel it at some point. If that’s true, you can use a context.Context to signal when you want a goroutine running in the background to stop.

For my particular application, yes I do want the go routine to run indefinitely. I have used a boolean channel to exit gracefully before. I have found that exiting the main loop (eg CTRL+C or exiting a GUI program written in Go for example) abruptly stops the Go routine, and this is to be expected. Utilizing a channel to trigger an event internally in the goroutine that runs deferred code etc. works well.

I was not aware of the context.context option, thanks. I’ll have to read up a bit more on that.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.