course/context/context-withtimeout.go

40 lines
661 B
Go
Raw Normal View History

2024-07-29 00:25:13 +08:00
package main
import (
"context"
"fmt"
"sync"
"time"
)
// context.WithTimeout
var Wg sync.WaitGroup
func worker(ctx context.Context) {
LOOP:
for {
fmt.Println("db connecting ...")
time.Sleep(time.Millisecond * 10) // 假设正常连接数据库耗时10毫秒
select {
case <-ctx.Done(): // 50毫秒后自动调用
break LOOP
default:
}
}
fmt.Println("worker done!")
Wg.Done()
}
func main() {
// 设置一个50毫秒的超时
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
Wg.Add(1)
go worker(ctx)
time.Sleep(time.Second * 5)
cancel() // 通知子goroutine结束
Wg.Wait()
fmt.Println("over")
}