SoFunction
Updated on 2025-03-02

One article will help you understand how Golang can correctly exit Goroutine

In Go, Goroutine is a lightweight thread, and its exit mechanism is crucial for concurrent programming. This article will introduce several Goroutine exit mechanisms and provide some sample code to illustrate the use of each mechanism.

Function or method has been executed

The most common way to exit Goroutine is to complete the execution of the function or method. When a function or method in a Goroutine is executed, the Goroutine will automatically exit.

Example:

package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		// The function in Goroutine will automatically exit after execution		("Goroutine execution complete")
	}()
	// Main Goroutine continues to perform other tasks	()
	("Main Goroutine execution complete")
}

In the example above, we create an anonymous Goroutine, print a message in it, and then the Goroutine is executed and automatically exits. The main Goroutine continues with other tasks.

Return statement

In Goroutine, we can explicitly exit using the return statement. When executing to the return statement, the Goroutine will terminate and return the corresponding result (if any).

Example:

package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		// Use the return statement in Goroutine to explicitly exit		("Goroutine execution")
		return
	}()
	// Main Goroutine continues to perform other tasks	()
	("Main Goroutine execution complete")
}

In the example above, we create an anonymous Goroutine, print a message in it, and then explicitly exit the Goroutine using the return statement.

() function

The () function can be used to directly terminate the execution of the current Goroutine without affecting other Goroutines. Calling() will immediately stop the execution of the current Goroutine, but will not cause the program to exit.

Example:

package main
import (
	"fmt"
	"runtime"
	"time"
)
func main() {
	go func() {
		// Use () to terminate the execution of the current Goroutine		("Goroutine execution before Goexit")
		()
		("Goroutine execution after Goexit") // won't execute here	}()
	// Main Goroutine continues to perform other tasks	()
	("Main Goroutine execution complete")
}

In the example above, we create an anonymous Goroutine, and use the() function to terminate the execution of the Goroutine.

panic() and recover()

If a panic occurs in a Goroutine, the execution of the current Goroutine is terminated by default and propagates up to the upper layer of the call stack. We can use the recover() function in Goroutine to catch and handle panics to avoid program crashes.

Example:

package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				//Catch and handle panic in Goroutine				("Recovered from panic:", err)
			}
		}()
		// Cause panic		panic("Goroutine panic")
	}()
	// Main Goroutine continues to perform other tasks	()
	("Main Goroutine execution complete")
}

In the example above, we create an anonymous Goroutine where panic() is used to cause panic. Then use defer and recover() to capture and handle panic, making sure the program does not crash.

Cancel

The Go language context package provides a mechanism to manage the life cycle of a Goroutine, including canceling running Goroutines. We can use the cancel() method to cancel the execution of the Goroutine. Once the Goroutine receives the cancel signal, it should exit as soon as possible.

Example:

package main
import (
	"context"
	"fmt"
	"time"
)
func worker(ctx ) {
	for {
		select {
		case <-():
			// Exit Goroutine after receiving the cancel signal			("Goroutine execution canceled")
			return
		default:
			// Perform normal tasks			("Goroutine executing...")
			()
		}
	}
}
func main() {
	ctx, cancel := (())
	go worker(ctx)
	// Simulate cancellation of tasks	(3 * )
	cancel()
	// Main Goroutine continues to perform other tasks	()
	("Main Goroutine execution complete")
}

In the example above, we create a worker function where we use select and () to determine whether a cancel signal is received. When the cancel signal arrives, Goroutine exits in time.

This blog introduces the exit mechanism of Goroutine in detail, including the completion of function or method execution, return statement, () function, panic() and recover(), and cancel mechanism. Understanding and proficient in applying these exit mechanisms is essential to writing reliable concurrent code.

This is the article about this article about how Golang correctly exits Goroutine. For more information about Go correctly exiting Goroutine, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!