哪个是更好的用于减少goroutine开销的代码?

huangapple go评论66阅读模式
英文:

which is one better code for goroutine overhead

问题

我想要使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?

英文:

I want to make Reader.Read concurrent with channel communication.
so I made two ways to run it

1:
<!-- language: go -->

type ReturnRead struct {
	n   int
	err error
}

type ReadGoSt struct {
	Returnc &lt;-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 &lt;- ReturnRead{n, err}
			if err != nil {
				return
			}
		}
	}()

	return &amp;ReadGoSt{returnc, nextc}
}

2:
<!-- language: go -->

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

i think code 2 creates too many overhead

which is the better code? 1? 2?

答案1

得分: 1

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

类似这样的代码:http://play.golang.org/p/zRPXOtdgWD

英文:

Code 1 is better and probably faster. Code 2 will just read once. But I think both solutions are not the best. you should loop over the read and send back only the bytes readed.

Something like : http://play.golang.org/p/zRPXOtdgWD

huangapple
  • 本文由 发表于 2015年1月10日 00:47:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/27865277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定