Skip to content

Instantly share code, notes, and snippets.

@ismdeep
Created January 15, 2020 14:22
Show Gist options
  • Save ismdeep/44b56aa0e349b3e696db515c4d486905 to your computer and use it in GitHub Desktop.
Save ismdeep/44b56aa0e349b3e696db515c4d486905 to your computer and use it in GitHub Desktop.
package main
import "sync"
type receiver struct {
sync.WaitGroup
data chan int
}
func newReceiver() *receiver {
r := &receiver{
data: make(chan int, 1000000),
}
r.Add(1)
go func(dataChan chan int) {
for x := range dataChan{
println("recv : ", x)
}
defer r.Done()
}(r.data)
return r
}
func main() {
r := newReceiver()
for i := 0; i < 100000; i++ {
r.data <- i
}
close(r.data)
r.Wait()
println("Done")
}
@ismdeep
Copy link
Author

ismdeep commented Jan 15, 2020

  1. 20 行的Done你也放错地方了。
  2. 还有应该就是内存自动回收机制干掉了你的 r 里面的内存。(猜测)

@ismdeep
Copy link
Author

ismdeep commented Jan 15, 2020

  1. 因为你变量实体是在函数 newReceiver() 里面的,那么出来之后就认为实体没有存在的必要了。可能会被自动回收掉。

@ismdeep
Copy link
Author

ismdeep commented Jan 15, 2020

image
这样写都行。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment