dourang6858 2017-07-15 08:39
浏览 44

如何检查conn写goroutine是否被阻止?

I'm writing a tcp bridge that pipes data from a conn to another conn, the process is duplex, that means the another conn may need to write data to the first conn.

I open four go-routines to handle the task, each one just does one of the things: read from upstream, write to downstream, read from downstream, and write to upstream. The read go-routine is simple:

func readUpstream(conn *net.TCPConn) {
    for {
        buf := make([]byte, 10)
        _, err := io.ReadFull(conn, buf)
        if err != nil {
            break
        }
        pipeToDownstream(buf)
    }
}

In general, the function pipeToDownload just need a channel to write to it, and the writeDownstream function just read the channel, and then write it to the downstream conn, just like follow:

func pipeToDownstream(buf) {
    downPipe <- buf
}

func writeDownstream(conn *net.Conn) {
    for {
        data := <- downPipe
        _, err := conn.Write(data)
        if err != nil {
            break
        }
    }
}

But, in my case, the data from upstream is a video stream, I need to ensure the real-time pipe, that means if the downstream is writing, just the last frame read from the upstream should be reserved, and then the write downstream routine read from the reserved data and then write it. Because the video stream needs big bandwidth, but sometimes the client bandwidth is not enough to send data, and then the write downstream routine will be blocked, and then if use pipeToDownstream function directly will block the readUpstream go routine.

So, I added a flag to represent the writeDownstream is writing, the read data from readUpstream should be reserved if the flag is 1, else should pipe to the channel directly. This means I need to add a mutex to ensure thread-safe for the flag and the reserved field.

How should I do?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 matlab有关常微分方程的问题求解决
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?
    • ¥100 求三轴之间相互配合画圆以及直线的算法