初始化Go学习项目
This commit is contained in:
38
go-select-practice/select_context.go
Normal file
38
go-select-practice/select_context.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 模拟一个可被取消的操作
|
||||
func doWork(ctx context.Context) error {
|
||||
for i := 1; i <= 5; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// context 被取消或超时
|
||||
fmt.Println("doWork 被取消:", ctx.Err())
|
||||
return ctx.Err()
|
||||
default:
|
||||
fmt.Println("工作中 step", i)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
fmt.Println("doWork 正常完成")
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
fmt.Println("开始工作,最长 3 秒...")
|
||||
|
||||
if err := doWork(ctx); err != nil {
|
||||
fmt.Println("结束,原因:", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("结束: 正常完成")
|
||||
}
|
||||
Reference in New Issue
Block a user