Timeouts
package main
import (
"fmt"
"time"
)
func main() {
// Creating a buffered channel 'c1' with a capacity of 1
c1 := make(chan string, 1)
// Launching a goroutine to send "result 1" to 'c1' after a 2-second delay
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
// The 'select' statement is used to either receive from 'c1' or timeout after 1 second
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
// Creating another buffered channel 'c2' with a capacity of 1
c2 := make(chan string, 1)
// Launching a goroutine to send "result 2" to 'c2' after a 2-second delay
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
// The 'select' statement is used to either receive from 'c2' or timeout after 3 seconds
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}Output
Last updated