V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  CarrieBauch  ›  全部回复第 3 页 / 共 3 页
回复总数  46
1  2  3  
@rekulas
明白了,多谢多谢
@aarontian
明白了,panic 会发生在所有的协程都被阻塞的情况下。把第一个程序简化为这样之后,也不会 panic 。因为 go 启动的一个协程在不断的运行,所以不会 panic

package main

func main() {
go func() {
for {
}
}()
var c chan bool
<-c
}
咦,玩 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  
关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   1004 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 430ms · UTC 22:49 · PVG 06:49 · LAX 14:49 · JFK 17:49
♥ Do have faith in what you're doing.