zl程序教程

您现在的位置是:首页 >  后端

当前栏目

0103-Go-超时处理

Go 处理 超时
2023-09-27 14:23:45 时间

环境

  • 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 语言的通道选择器来处理超时。

附录