使用场景
主要有下面两点:
- 控制一组关联的goroutine的生命周期,WithCancel,WithTimeout,WithDeadline,WithTimeout
- 在一组关联的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
深入内部
避坑指南
https://studygolang.com/articles/10792?fr=sidebar
https://deepzz.com/post/golang-context-package-notes.html
有疑问加站长微信联系(非本文作者)