MCPcopy Create free account
hub / github.com/SKeyerror/Psyduck / TestTimeOutFunction

Function TestTimeOutFunction

go-concurrency/channel/goroutine_leak_test.go:36–52  ·  view source on GitHub ↗

这里有一个关于 GC 的问题,假如下面儿的 ch 中装的堆变量,那么当函数运行结束后,ch 会被 GC 回收掉吗? channel 源码: https://github.com/golang/go/blob/2ebe77a2fda1ee9ff6fd9a3e08933ad1ebaea039/src/runtime/chan.go#L355 一个比较有意思的地方在于,channel 的 close 方法并没有去清理环形队列 buf 中的内容,仅仅只是清理了两个阻塞队列中的内容, 这和 channel 的行为是一致的: 当我们关闭了一个 channel 以后,receiver 仍然可以继续读取 ch

(t *testing.T)

Source from the content-addressed store, hash-verified

34// 这和 channel 的行为是一致的: 当我们关闭了一个 channel 以后,receiver 仍然可以继续读取 channel 中的内容,直到没有任何数据
35// 如果 buf 中有内容的 ch 可以被回收,那么是什么时候被 GC 的呢? GC 又是通过什么条件去判断 channel 可以被回收的呢?
36func TestTimeOutFunction(t *testing.T) {
37 ch := make(chan struct{}, 1)
38
39 go func() {
40 // 模拟耗时任务
41 time.Sleep(5 * time.Second)
42 // 任务执行完毕后向外发出通知
43 ch <- struct{}{}
44 }()
45
46 select {
47 case <-ch:
48 fmt.Println("Task Done")
49 case <-time.After(2 * time.Second):
50 fmt.Println("Time Limit Exceeded")
51 }
52}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected