美文网首页
golang context 初步

golang context 初步

作者: 郭青耀 | 来源:发表于2020-08-20 15:13 被阅读0次

使用场景

主要有下面两点:

  1. 控制一组关联的goroutine的生命周期,WithCancel,WithTimeout,WithDeadline,WithTimeout
  2. 在一组关联的goroutine之间传递数据,WithValue

具体实例

1. WithCancel 实例,一个cancel操作,取消掉所有的子goroutine

package main

import (
    "context"
    "fmt"
    "time"
)

func worker(ctx context.Context, value string) {
    go func() { // 必须是gorouting才会有context之间的通信
        for { //这里的死循环+外加sleep才能不断的循环调度
            select {
            case <-ctx.Done():
                fmt.Println(value, "is called")
                return //保证死循环可以跳出
            default:
                fmt.Println("wait " + value + " context done")
                time.Sleep(time.Second) //保证死循环可以切换出去
            }
        }
    }()
}

func main() {
        // context.Background() 看作是一组关联的goroutine的根节点
    ctx, cancel := context.WithCancel(context.Background())
    worker(ctx, "node1")
    worker(ctx, "node2")
    worker(ctx, "node3")
    time.Sleep(2 * time.Second)
    cancel() //这里执行cancel()操作,所有的ctx  都被cancel掉了。
    time.Sleep(2 * time.Second)
}

输出结果

wait node1 context done
wait node2 context done
wait node3 context done
wait node2 context done
wait node1 context done
wait node3 context done
node2 is called
node1 is called
node3 is called

1. WithTimeout 实例,超时,取消掉所有的子goroutine

package main

import (
    "context"
    "fmt"
    "time"
)

func worker(ctx context.Context, value string) {
    go func() { // 必须是gorouting才会有context之间的通信
        for { //这里的死循环+外加sleep才能不断的循环调度
            select {
            case <-ctx.Done():
                fmt.Println(value, "is called")
                return //保证死循环可以跳出
            default:
                fmt.Println("wait " + value + " context done")
                time.Sleep(time.Second) //保证goroutine可以正常的切换出去
            }
        }
    }()
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    worker(ctx, "node1")
    worker(ctx, "node2")
    worker(ctx, "node3")
    time.Sleep(3 * time.Second)
}

实际输出效果

wait node3 context done
wait node1 context done
wait node2 context done
wait node2 context done
wait node1 context done
wait node3 context done
node2 is called
node3 is called
node1 is called

4. WithValue 实例,在goroutine中间传递数值

package main

import (
    "context"
    "fmt"
    "time"
)

func GetContextValue(ctx context.Context, key string) {
    go func() {
        for {
            select {
            case <-ctx.Done():
                if value := ctx.Value(key); value != nil {
                    fmt.Println("get value is ", value)
                } else {
                    fmt.Println("Can't get value from key", key)
                }
                return
            default:
                fmt.Println(key, "wait for run")
                time.Sleep(1 * time.Second)
            }

        }

    }()

}
func main() {
    root := context.Background()
    withValue := context.WithValue(root, "lang", "Golang")
    ctx, cancelFuc := context.WithCancel(withValue)
    GetContextValue(ctx, "lang")
    GetContextValue(ctx, "lang1")
    cancelFuc()
    time.Sleep(2 * time.Second)
}

结果输出

get value is  Golang
Can't get value from key lang1

相关文章

  • golang context 初步

    使用场景 主要有下面两点: 控制一组关联的goroutine的生命周期,WithCancel,WithTimeou...

  • Go context源码解析

    在上一篇文章 golang context初探 中,已经初步了解了context的用法以及应用的场景。那么接下来深...

  • Golang Context分析

    [TOC] Golang Context分析 Context背景 和 适用场景 golang在1.6.2的时候还没...

  • 利用context保存数据

    context[https://golang.org/pkg/context/#example_WithValue...

  • Golang 之context库用法

    1. context Golang 中的context 是Go语言在 golang1.7 发布时新增的标准包目的...

  • Golang Context 详细原理和使用技巧

    Golang Context 详细原理和使用技巧 Context 背景 和 适用场景 Context 的背景 Go...

  • Golang context初探

    什么是context 从go1.7开始,golang.org/x/net/context包正式作为context包...

  • golang context

    overview Package context defines the Context type, which ...

  • golang context

    https://yq.aliyun.com/articles/69662https://deepzz.com/po...

  • golang context

    在 go1.7 及以上版本 context 包被正式列入官方库中,所以我们只需要import "context"就...

网友评论

      本文标题:golang context 初步

      本文链接:https://www.haomeiwen.com/subject/ungbrktx.html