有一个函数,要并发访问好几个数据库,返回时间不一样,就叫做 longTimeTask()吧,我想用 context 设置超时,现在试下了,context 声明放在 main 里面,就所有 goroutine 共享了,不符合我要求,如果这样是可以的:
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
longTimeTask(ctx)
}()
后面我发现这样也行:
func longTimeTask(){
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
}
所以想问问哪种最合适