zoukankan      html  css  js  c++  java
  • golang学习笔记——context库

    WithCancel(主进程控制子协程关闭)
    package main
     
    import (
        "context"
        "fmt"
        "sync"
        "time"
    )
     
    var wg sync.WaitGroup
     
    func f(ctx context.Context) {
        defer wg.Done()
        LOOP:
        for {
             fmt.Println("hello world")
             time.Sleep(time.Millisecond * 500)
             select {
             case <-ctx.Done():
                     break LOOP
             default:
             }
        }
    }
     
    func main() {
        ctx, cancel := context.WithCancel(context.Background())
        wg.Add(1)
        go f(ctx)
        time.Sleep(time.Second * 5)
        //通知子协程退出
        cancel()
        wg.Wait()
    }
     
    WithTimeout(超时关闭)
    package main
     
    import (
        "context"
        "fmt"
        "sync"
        "time"
    )
     
    var wg sync.WaitGroup
     
    func f(ctx context.Context) {
        defer wg.Done()
        LOOP:
        for {
             fmt.Println("hello world")
             time.Sleep(time.Millisecond * 500)
             select {
             case <-ctx.Done(): //50毫秒自动调用
                     break LOOP
             default:
             }
        }
    }
     
    func main() {
        ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
        //通知子协程退出
        defer cancel()
        wg.Add(1)
        go f(ctx)
        time.Sleep(time.Second * 5)
        wg.Wait()
    }
     
    WithValue (key值不能为基础类型,应该用用户自定义的类型
    package main
     
    import (
        "context"
        "fmt"
        "sync"
        "time"
    )
     
    type cjp string
     
    var wg sync.WaitGroup
     
    func f(ctx context.Context) {
        defer wg.Done()
        LOOP:
        for {
             fmt.Println(ctx.Value(cjp("mt")))
             fmt.Println("hello world")
             time.Sleep(time.Millisecond * 500)
             select {
             case <-ctx.Done(): //50毫秒自动调用
                     break LOOP
             default:
             }
        }
    }
     
    func main() {
        ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
        defer cancel()
        ctx = context.WithValue(ctx, cjp("mt"), "cuijiapeng")
        wg.Add(1)
        go f(ctx)
        time.Sleep(time.Second * 5)
        wg.Wait()
    }
     
     
  • 相关阅读:
    BZOJ4896 THUSC2016补退选(trie)
    BZOJ4892 Tjoi2017dna(后缀数组)
    BZOJ4890 Tjoi2017城市
    BZOJ4888 Tjoi2017异或和(树状数组)
    BZOJ4887 Tjoi2017可乐(动态规划+矩阵快速幂)
    BZOJ4883 棋盘上的守卫(环套树+最小生成树)
    BZOJ4881 线段游戏(二分图+树状数组/动态规划+线段树)
    BZOJ4878 挑战NP-Hard(dfs树)
    BZOJ5466 NOIP2018保卫王国(倍增+树形dp)
    BZOJ4873 Shoi2017寿司餐厅(最小割)
  • 原文地址:https://www.cnblogs.com/itsuibi/p/14490159.html
Copyright © 2011-2022 走看看