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

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

which is one better code for goroutine overhead

问题

我想要使Reader.Read与通道通信并发进行。所以我有两种运行方式。

1:

  1. type ReturnRead struct {
  2. n int
  3. err error
  4. }
  5. type ReadGoSt struct {
  6. Returnc <-chan ReturnRead
  7. Nextc chan struct{}
  8. }
  9. func (st *ReadGoSt) Close() {
  10. defer func() {
  11. recover()
  12. }()
  13. close(st.Next)
  14. }
  15. func ReadGo(r io.Reader, b []byte) *ReadGoSt {
  16. returnc := make(chan ReturnRead)
  17. nextc := make(chan bool)
  18. go func() {
  19. for range nextc {
  20. n, err := r.Read(b)
  21. returnc <- ReturnRead{n, err}
  22. if err != nil {
  23. return
  24. }
  25. }
  26. }()
  27. return &ReadGoSt{returnc, nextc}
  28. }

2:

  1. func ReadGo(r io.Reader, b []byte) <-chan ReturnRead {
  2. returnc := make(chan ReturnRead)
  3. go func() {
  4. n, err := r.Read(b)
  5. returnc <- ReturnRead{n, err}
  6. }()
  7. return returnc
  8. }

我认为代码2会产生太多的开销。哪个代码更好?是1还是2?

英文:

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

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

  1. type ReturnRead struct {
  2. n int
  3. err error
  4. }
  5. type ReadGoSt struct {
  6. Returnc &lt;-chan ReturnRead
  7. Nextc chan struct{}
  8. }
  9. func (st *ReadGoSt) Close() {
  10. defer func() {
  11. recover()
  12. }()
  13. close(st.Next)
  14. }
  15. func ReadGo(r io.Reader, b []byte) *ReadGoSt {
  16. returnc := make(chan ReturnRead)
  17. nextc := make(chan bool)
  18. go func() {
  19. for range nextc {
  20. n, err := r.Read(b)
  21. returnc &lt;- ReturnRead{n, err}
  22. if err != nil {
  23. return
  24. }
  25. }
  26. }()
  27. return &amp;ReadGoSt{returnc, nextc}
  28. }

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

  1. func ReadGo(r io.Reader, b []byte) &lt;-chan ReturnRead {
  2. returnc := make(chan ReturnRead)
  3. go func() {
  4. n, err := r.Read(b)
  5. returnc &lt;- ReturnRead{n, err}
  6. }()
  7. return returnc
  8. }

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:

确定