Search⌘ K
AI Features

Timing Out a Goroutine

Explore techniques for timing out goroutines in Go to manage long-running or unresponsive tasks effectively. Learn practical approaches using the time.After function and select statements both inside and outside the main function. This lesson helps you prevent program blocking by implementing reliable timeout controls for goroutines in concurrent Go applications.

There are times that goroutines take more time than expected to finish—in such situations, we want to time out the goroutines so that we can unblock the program. This lesson presents two such techniques.

Timing out a goroutine – inside main()

Let’s discuss a simple technique for timing out a goroutine.

Coding example

The relevant code can be found in the main() function of timeOut1.go:

Go (1.19.0)
func main() {
c1 := make(chan string)
go func() {
time.Sleep(3 * time.Second)
c1 <- "c1 OK"
}()

The time.Sleep() call is used for emulating the time it normally takes for a function to finish its operation. In this case, the anonymous function that is executed as a goroutine takes about three seconds before writing a message ...