dsjq62428 2018-03-06 17:26
浏览 98
已采纳

如何停止从UDP读取的goroutine?

I have a go program that uses a goroutine to read UDP packets. I wanted to use a select clause and a "stopping" channel to close the goroutine to shut down as soon as it is not needed anymore.

Here is a simple code example for the goroutine:

func Run(c chan string, q chan bool, conn *net.UDPConn) {

    defer close(c)

    buf := make([]byte, 1024)

    for {
        select {
            case <- q:
                return
            default:
                n, _, err := conn.ReadFromUDP(buf)
                c <- string(buf[0:n])
                fmt.Println("Received ", string(buf[0:n]))

                if err != nil {
                    fmt.Println("Error: ", err)
                }
        }
    }
}

The connection is created as:

    conn, err := net.ListenUDP("udp",addr.Addr)

And the goroutine is supposed to terminate using:

    close(q)

After closing the "stopping" channel ("q") the goroutine does not immediately stop. I need to send one more string via the UDP connection. When doing so the goroutine stops. I simply do not understand this behaviour and I would be grateful if somebody could enlighten me.

Thank you in advance!

  • 写回答

1条回答 默认 最新

  • duanchu3376 2018-03-06 18:25
    关注

    Your program is likely stopped at this line when you close the channel:

    n, _, err := conn.ReadFromUDP(buf)
    

    Because execution is blocked at a ReadFrom method, the select statement is not being evaluated, therefore the close on channel q is not immediately detected. When you do another send on the UDP connection, ReadFrom unblocks and (once that loop iteration finishes) control moves to the select statement: at that point the close on q is detected.

    You can close the connection to unblock ReadFrom, as was suggested in a comment. See the PacketConn documentation in the net package, especially "Any blocked ReadFrom or WriteTo operations will be unblocked and return errors":

    // Close closes the connection.
    // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
    Close() error
    

    Depending on your needs a timeout might be an option as well, see again PacketConn documentation in the net package:

     // ReadFrom reads a packet from the connection,
     // copying the payload into b. It returns the number of
     // bytes copied into b and the return address that
     // was on the packet.
     // ReadFrom can be made to time out and return
     // an Error with Timeout() == true after a fixed time limit;
     // see SetDeadline and SetReadDeadline.
     ReadFrom(b []byte) (n int, addr Addr, err error)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析