首页 > 其他分享 >Go - context

Go - context

时间:2024-02-23 11:56:41浏览次数:22  
标签:timed second sleep context Go main out

 

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
    defer cancel()

    go f1(ctx)

    for i := 0; i < 10; i++ {
        select {
        case <-ctx.Done():
            fmt.Println("timed out")
        default:
            fmt.Println("main sleep for 1 second")
            time.Sleep(time.Second)
        }
    }

    time.Sleep(30 * time.Second)
    fmt.Println("main slept for 30 seconds")
}

func f1(ctx context.Context) {
    go f2()

    time.Sleep(10 * time.Second)
    fmt.Println("f1 slept for 10 seconds")
}

func f2() {
    time.Sleep(20 * time.Second)
    fmt.Println("f2 slept for 20 seconds")
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
timed out
timed out
timed out
timed out
f1 slept for 10 seconds
f2 slept for 20 seconds
main slept for 30 seconds

From the output, we can see that context timing out cannot stop goroutines from executing.

 

context.Context can only relay the message that timeout or cancellation happened. It does not have the power to actually stop any goroutines (for details, see cancel a blocking operation in Go). The goroutine itself is responsible for checking the timeout and cancellation, and abort early.

 

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
    defer cancel()

    go f1(ctx)

    for i := 0; i < 10; i++ {
        select {
        case <-ctx.Done():
            fmt.Println("timed out")
        default:
            fmt.Println("main sleep for 1 second")
            time.Sleep(time.Second)
        }
    }

    time.Sleep(30 * time.Second)
    fmt.Println("main slept for 30 seconds")
}

func f1(ctx context.Context) {
    go f2()

    select {
    case <-ctx.Done():
        fmt.Println(ctx.Err())
    case <-time.After(10 * time.Second):
        fmt.Println("f1 slept for 10 seconds")
    }
}

func f2() {
    time.Sleep(20 * time.Second)
    fmt.Println("f2 slept for 20 seconds")
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
main sleep for 1 second
context deadline exceeded
timed out
timed out
timed out
timed out
timed out
f2 slept for 20 seconds
main slept for 30 seconds

 

标签:timed,second,sleep,context,Go,main,out
From: https://www.cnblogs.com/zhangzhihui/p/18029200

相关文章

  • Go 100 mistakes - #61: Propagating an inappropriate context
       疑问:前两种情况(1.客户端连接中断2.HTTP请求取消)发生,publish却不expire也不会被cancel,这样会不会有问题? ......
  • 欢迎 Gemma: Google 最新推出开源大语言模型
    今天,Google发布了一系列最新的开放式大型语言模型——Gemma!Google正在加强其对开源人工智能的支持,我们也非常有幸能够帮助全力支持这次发布,并与HuggingFace生态完美集成。Gemma提供两种规模的模型:7B参数模型,针对消费级GPU和TPU设计,确保高效部署和开发;2B参数模型则......
  • Go - Contexts
           ......
  • Go - memory model
     Receivingfromanemptyunbufferedchannelcausedthechildgoroutineexit.  ......
  • CF1398C Good Subarrays(写给我们萌新团体)
    GoodSubarrays传送门:GoodSubarrays-洛谷|计算机科学教育新生态(luogu.com.cn)思路暴力!!!!!一如既往的暴力!!!复杂度O(n^2)数据n到1e5TLE必定TLE我们可以用一个桶来优化实质上其实还是高中所学的排列组合思想第一步:当然是前缀和了,这边讲给新手写一下,有点冗杂,是高手直接......
  • golang中的接口(数据类型)
    golang中的接口Golang中的接口是一种抽象数据类型,Golang中接口定义了对象的行为规范,只定义规范不实现。接口中定义的规范由具体的对象来实现,通俗的讲接口就一个标准,它是对一个对象的行为和规范进行约定,约定实现接口的对象必须得按照接口的规范接口的定义在go中接口(int......
  • golang中的类型断言,解释.(float64)和.(string)
    在Go语言中,. 后跟括号中的类型名称(如 .(float64) 或 .(string))通常出现在类型断言(typeassertion)的上下文中。类型断言用于检查一个空接口(interface{})值是否包含特定的类型,如果是,则将其转换为该类型。类型断言的语法如下:value,ok:=x.(T)其中 x 是一个 interface{}......
  • 推荐两个网络复用相关的 Go pkg: cmux smux
    推荐两个网络复用相关的Gopkg:cmux/smux只写一下如何使用,不对实现进行大量描述,两个库的代码都比较精炼,花一会看一下就行。cmux对端口进行复用,单端口可以建立不同协议的连接(本质都是TCP),如TCP/TLS/HTTP/gRPC或自定义协议smux对TCP连接复用,单TCP连接承载多条smuxstream......
  • Go - Data races vs. race conditions
         ......
  • Golang Gorm 的标签tag
    当使用GORM进行数据库模型映射时,可以使用多种标签来定义字段的行为。以下是一些常用的GORM标签:gorm:"primary_key":定义字段作为模型的主键。gorm:"column:<column_name>":指定字段在数据库表中的列名。gorm:"type:<data_type>":指定字段的数据库数据类型。gorm:"......