0103-Go-超时处理

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/timeouts

目标

使用 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")
    }
}

总结

使用 Go 语言的通道选择器来处理超时。

附录

posted @ 2022-10-30 08:37  jiangbo4444  阅读(34)  评论(0)    收藏  举报