【发布时间】:2021-11-28 18:27:32
【问题描述】:
我正在尝试停止子(或链接的)go 通道,但操作被阻塞(例如,具有等待网络连接的侦听器)
因为操作是阻塞的,所以for和case永远不会进入case
如何解决?
package main
import (
"fmt"
"time"
)
func main() {
quit := make(chan bool)
fmt.Println("Starting Channel 001")
go func() {
for {
select {
case <-quit:
fmt.Println("Channel 001 stopped")
// Expected result: hangFunction stop execution looping
return
default:
hangFunction()
time.Sleep(1 * time.Second)
}
}
}()
time.Sleep(2 * time.Second)
fmt.Println("Closing channel 001")
close(quit)
time.Sleep(1 * time.Hour)
}
func hangFunction() {
for {
fmt.Println("[hangFunction] Looping")
time.Sleep(1 * time.Second)
}
}
【问题讨论】:
-
您必须在
hangFunction内监控频道。 -
通过关闭监听器来解锁网络操作。显示阻塞的实际代码会很有帮助。