首次提交:初始化项目代码
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 监听上下文信号的任务函数
|
||||
func runTask(ctx context.Context, taskName string) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
fmt.Printf("任务[%s]:收到退出信号,终止执行\n", taskName)
|
||||
return
|
||||
default:
|
||||
fmt.Printf("任务[%s]:运行中...\n", taskName)
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 1. 创建父上下文
|
||||
parentCtx, cancelParent := context.WithCancel(context.Background())
|
||||
defer cancelParent()
|
||||
|
||||
// 2. 派生两个子上下文
|
||||
childCtx1, _ := context.WithCancel(parentCtx)
|
||||
childCtx2, _ := context.WithCancel(parentCtx)
|
||||
|
||||
// 3. 启动协程执行任务
|
||||
go runTask(childCtx1, "子任务1")
|
||||
go runTask(childCtx2, "子任务2")
|
||||
|
||||
// 4. 主协程运行2秒后取消父上下文
|
||||
fmt.Println("主协程:2秒后取消所有子任务")
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
fmt.Println("\n主协程:取消父上下文")
|
||||
cancelParent()
|
||||
|
||||
// 等待协程优雅退出
|
||||
time.Sleep(1 * time.Second)
|
||||
fmt.Println("主协程:所有任务已退出")
|
||||
}
|
||||
Reference in New Issue
Block a user