【问题标题】:which is one better code for goroutine overhead这是 goroutine 开销的一种更好的代码
【发布时间】:2015-03-08 01:15:21
【问题描述】:

我想让 Reader.Read 与通道通信并发。 所以我做了两种方法来运行它

1:

type ReturnRead struct {
    n   int
    err error
}

type ReadGoSt struct {
    Returnc <-chan ReturnRead
    Nextc chan struct{}
}

func (st *ReadGoSt) Close() {
    defer func() {
        recover()
    }()
    close(st.Next)
}

func ReadGo(r io.Reader, b []byte) *ReadGoSt {
    returnc := make(chan ReturnRead)
    nextc := make(chan bool)

    go func() {
        for range nextc {
            n, err := r.Read(b)
            returnc <- ReturnRead{n, err}
            if err != nil {
                return
            }
        }
    }()

    return &ReadGoSt{returnc, nextc}
}

2:

func ReadGo(r io.Reader, b []byte) <-chan ReturnRead {
    returnc := make(chan ReturnRead)
    go func() {
        n, err := r.Read(b)
        returnc <- ReturnRead{n, err}
    }()
    return returnc
}

我认为代码 2 产生了太多开销

哪个代码更好? 1? 2?

【问题讨论】:

    标签: go overhead goroutine


    【解决方案1】:

    代码 1 更好,可能更快。代码 2 只会读取一次。但我认为这两种解决方案都不是最好的。您应该循环读取并仅发送回读取的字节。

    类似:http://play.golang.org/p/zRPXOtdgWD

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      相关资源
      最近更新 更多