V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
V2EX  ›  CarrieBauch  ›  全部回复第 4 页 / 共 4 页
回复总数  64
1  2  3  4  
咦,玩 V 站不久,回复里面竟然无法使用 markdown 格式
@mcfog
谢谢你,程序改为下面的这样的,就清晰很多了。

结论就是你说的,不是 defer cancel() 让 -ctx.Done()。而是时间到了之后,ctx.Done 里面就会有消息写入了。

defer cancel() 其实就是一个兜底的策略,可以取保 main 返回的时候,可以 cancel 掉

```
package main

import (
"context"
"fmt"
"time"
)

const shortDuration = 1 * time.Second

func main() {
timeNow := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
//defer cancel()
defer func() {
time.Sleep(5 * time.Second)
fmt.Println(1111)
cancel()
}()
select {
case <-time.After(2 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
fmt.Println(time.Since(timeNow))

}

```
2023 年 6 月 26 日
回复了 CarrieBauch 创建的主题 Go 编程语言 一段 Go 代码输出疑惑
@eastphoton @iyear

感谢两位大佬的回复。

再次打扰一下。针对这类型的问题,有没有什么书籍或者文章系统性的介绍吗?想去查漏补缺一下,补齐知识的盲点
2023 年 6 月 24 日
回复了 CarrieBauch 创建的主题 Go 编程语言 一段 Go 代码输出疑惑
@iyear 有道理,多谢解答。race condition 真是防不胜防
1  2  3  4  
About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1104 Online   Highest 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 10ms · UTC 23:26 · PVG 07:26 · LAX 16:26 · JFK 19:26
♥ Do have faith in what you're doing.