初始化Go学习项目
This commit is contained in:
35
go-context-practice/cancel_basic.go
Normal file
35
go-context-practice/cancel_basic.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 模拟一个可被取消的循环任务
|
||||
func worker(ctx context.Context, name string) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
fmt.Println(name, "收到取消信号:", ctx.Err())
|
||||
return
|
||||
default:
|
||||
fmt.Println(name, "还在干活...")
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
go worker(ctx, "worker-1")
|
||||
go worker(ctx, "worker-2")
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
fmt.Println("main: 决定取消所有 worker")
|
||||
cancel() // 发出取消信号
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
fmt.Println("main 结束")
|
||||
}
|
||||
Reference in New Issue
Block a user