前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang学习笔记——context库

golang学习笔记——context库

作者头像
码缘
发布2021-03-09 16:52:25
3380
发布2021-03-09 16:52:25
举报
文章被收录于专栏:PHP修行之路

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()

}

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-03-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档