[13th][Day21] golang context

context 是个处理流程中关於『超时限制』的控制器

lib context
https://pkg.go.dev/[email protected]

常用的 context 方法

WithCancel: cancellation
WithDeadline and WithTimeout: deadline/timeout and cancellation
WithValue: key-value pairs

来看看几个例子

    ctx, cancel := context.WithCancel(context.Background())

	time.AfterFunc(4*time.Second, func() {
		cancel()
	})

	go func() {
		<-ctx.Done()
		fmt.Println("Context done!")
	}()

	go func() {
		time.Sleep(1 * time.Second)
		fmt.Println("After 1 second:", ctx.Err())
	}()

	go func() {
		time.Sleep(3 * time.Second)
		fmt.Println("After 3 seconds:", ctx.Err())
	}()

	go func() {
		time.Sleep(5 * time.Second)
		fmt.Println("After 5 seconds:", ctx.Err())
	}()

	time.Sleep(6 * time.Second)

上述例子中,会在第四秒时发出 cancel() 讯号
输出为

After 1 second: <nil>
After 3 seconds: <nil>
Context done!
After 5 seconds: context canceled

第五秒时 本 context 已 cancel


第二个例子


    ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
	_ = cancel // 本例中不使用 cancel

	go func() {
		<-ctx.Done()
		fmt.Println("Context done!")
	}()

	go func() {
		time.Sleep(1 * time.Second)
		fmt.Println("After 1 second:", ctx.Err())
	}()

	go func() {
		time.Sleep(3 * time.Second)
		fmt.Println("After 3 seconds:", ctx.Err())
	}()

	go func() {
		time.Sleep(5 * time.Second)
		fmt.Println("After 5 seconds:", ctx.Err())
	}()

	time.Sleep(6 * time.Second)

上述例子中,使用 WithTimeout 设定本 context 会在第四秒时超时
输出为

After 1 second: <nil>
After 3 seconds: <nil>
Context done!
After 5 seconds: context deadline exceeded

第三个例子


    ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)

	time.AfterFunc(2*time.Second, func() {
		cancel()
	})

	go func() {
		<-ctx.Done()
		fmt.Println("Context done!")
	}()

	go func() {
		time.Sleep(1 * time.Second)
		fmt.Println("After 1 second:", ctx.Err())
	}()

	go func() {
		time.Sleep(3 * time.Second)
		fmt.Println("After 3 seconds:", ctx.Err())
	}()

	go func() {
		time.Sleep(5 * time.Second)
		fmt.Println("After 5 seconds:", ctx.Err())
	}()

	time.Sleep(6 * time.Second)

同时使用 WithTimeout & cancel()
context 在 cancel 後就不会 time out 了

输出为

After 1 second: <nil>
Context done!
After 3 seconds: context canceled
After 5 seconds: context canceled

context 可以确保处理流程的安全性(thread-safe),更准确的是指 goroutine-safe
context 是不可变动的,只能基於现有的 context 创出新的 子 context


<<:  内容传递网路是什麽?网站停机的可能原因

>>:  使用 Ubuntu Server 与 Docker 建立 Gitea 程序储存库

Day 3 - 条件式

条件式就是小学常写的造样造句:如果...就(否则)...的概念。 这边会介绍几种常用的条件式语句 i...

[Day8] IoT Maker之Coding知识科普 - (缩排&条件逻辑判断)

1.前言 在各式各样的程序语言中,都有属於自己的语系,像是Arduino就偏向於C语言,而每种语言都...

[前端暴龙机,Vue2.x 进化 Vue3 ] Day19.组件练习 ref -分页(二)

今天我们会利用上一篇的 分页组件 范例来做更改,不过差别在於,这次我们父子组件的沟通不是透过 pro...

Day3 资料储存 - block storage优缺点及场景

优缺点 优点 Block storage最大的优点就是他使得计算与储存分离,我们能轻易地透过LUN ...

【第二天 - Flutter 继承+建构子+CallBack 基本概念】

前言 今日的程序码 => GITHUB 继承 Flutter 会有三个方式 Extends 当...