突破具有无限循环的第 3 方 goroutine

Break out of 3rd party goroutine that has an infinite loop

我正在使用它来接收 SNMP 陷阱:https://github.com/soniah/gosnmp 现在,假设我想以编程方式突破(取自 here):

err := tl.Listen("0.0.0.0:9162")

我最好的方法是什么?

我对 Golang 有点陌生,没有找到一种方法来突破我无法修改的 goroutine(“第 3 方”)。

谢谢,

简答:你不能。没有办法从 goroutine 外部杀死 goroutine(除了杀死整个程序)。

长答案:goroutine 可以监听某种 "terminate" 信号(通过通道、信号或任何其他机制)。但最终,goroutine 必须从 .

中终止

查看示例中的库,似乎未提供此功能。

标准https://golang.org/pkg/net/#Conn interface provides special methods SetDeadline (together with SetReadDeadline and SetWriteDeadline) to set a hard connection break time for staled connections. As I see in the source代码:

type GoSNMP struct {
    // Conn is net connection to use, typically established using GoSNMP.Connect()
    Conn net.Conn
     ...

    // Timeout is the timeout for the SNMP Query
    Timeout time.Duration
    ...

net.Conn 接口已导出 - 因此您可以尝试直接访问它以设置截止日期。

type TrapListener struct {
    OnNewTrap func(s *SnmpPacket, u *net.UDPAddr)
    Params    *GoSNMP
    ...
}

依次 TrapListener 导出 GoSNMP 结构,因此您可以访问它。试试这个:

tl := TrapListener{...}
tl.Params.Conn.SetDeadline(time.Now().Add(1*time.Second))
tl.Listen(...)

然而 this line 让我感到不安 - 看起来它不使用存储的连接及其选项:

func (t *TrapListener) Listen(addr string) (err error) {
    ...
    conn, err := net.ListenUDP("udp", udpAddr)
    ....
}

不过你可以试试:)