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()
}
原文地址:https://cloud.tencent.com/developer/article/1799218
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。