英文:
Will golang garbage collecting channel of pointers when it's dequeued from channel?
问题
如果我有这样的代码:
requests := make(chan *RequestStruct, 1000 * 1000)
responses := make(chan *ResponseStruct, 1000 * 1000)
如果所有的requests
和responses
已经被出队/消费完了,之前存在的指针最终会被垃圾回收,对吗?(或者不会被回收,因为没有人将其设置为nil)
英文:
If I have something like this:
requests := make(chan *RequestStruct, 1000 * 1000)
responses := make(chan *ResponseStruct, 1000 * 1000)
If the all requests
and responses
already dequeued/consumed, those pointers that previously was there would someday will be garbage collected right? (or it won't because nobody ever set it to nil on the channel?)
答案1
得分: 3
通道在runtime/chan.go
中实现。从缓冲通道读取是通过函数chanrecv
实现的,它执行以下操作:
qp := chanbuf(c, c.recvx)
typedmemmove(c.elemtype, ep, qp)
typedmemclr(c.elemtype, qp)
通道中存储的元素通过typedmemclr
清除,因此不会阻止指向的元素被垃圾回收。
英文:
Channels are implemented in runtime/chan.go
. Reading from a buffered channel is implemented by the function chanrecv
, which does the following:
qp := chanbuf(c, c.recvx)
typedmemmove(c.elemtype, ep, qp)
typedmemclr(c.elemtype, qp)
The element that is stored in the channel is cleared by the typedmemclr
, and will therefore not prevent the pointed-at element from being garbage-collected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论