douyu7618 2015-07-18 15:07
浏览 302

Go-从多个读取器从TCP连接读取数据

I'm working on Cloud Server's networking thing using Go programming language. And I faced a problem with reading same TCPconn at the same time from different Goroutines.

Here is a simple example

package main

import (
    "fmt"
    "net"
)

func main() {
    addr, _ := net.ResolveTCPAddr("tcp", ":8888")
    listener, _ := net.ListenTCP("tcp", addr)

    for {
        conn, err := listener.AcceptTCP()
        if err != nil {
            fmt.Println(err)
            return
        }
        go Handle(conn) // output always coming from here
        go Handle(conn)
    }
}

func Handle(conn *net.TCPConn) {
    data := make([]byte, 1024)
    fmt.Println("Ok")
    for {
        len_data, err := conn.Read(data)
        fmt.Println(err)
        fmt.Println(len_data)
    }
}

In this example console output always coming from 1st goroutine go Handle(conn) ...

How to make Read functionality from 2 Goroutines at the same time ?

Thanks

  • 写回答

3条回答 默认 最新

  • doo58088 2015-07-18 15:26
    关注

    Start a single go routine to perform conn.Read(data) and put the result into a channel.

    Then (concurrently, without waiting for the first go routine to finish) start multiple go routines to read from this channel.

    You don't want to directly read from the conn concurrently from multiple go routine since it is not thread-safe (the fact that it runs, and only run only on a single go routine probably because your MAXGOPROCS == 1).

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog