Go by Example: Timeouts

A timeout is an upper bound on the amount of time that can be spent waiting for an operation to complete. Here’s an example to demonstrate timeouts in Go:

package main

import (
	"fmt"
	"time"
)

func main() {
	c1 := make(chan string, 1)
	go func() {
		time.Sleep(2 * time.Second)
		c1 <- "result 1"
	}()

	select {
	case res := <-c1:
		fmt.Println(res)
	case <-time.After(1 * time.Second):
		fmt.Println("timeout 1")
	}

	c2 := make(chan string, 1)
	go func() {
		time.Sleep(2 * time.Second)
		c2 <- "result 2"
	}()
	select {
	case res := <-c2:
		fmt.Println(res)
	case <-time.After(3 * time.Second):
		fmt.Println("timeout 2")
	}
}

In the example above, the first select case will timeout after 1 second, and the second select case will receive a value from c2 after 2 seconds. The output of the program will be:

timeout 1
result 2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *