当从通道中出队时,Golang会对指针进行垃圾回收吗?

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

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)

如果所有的requestsresponses已经被出队/消费完了,之前存在的指针最终会被垃圾回收,对吗?(或者不会被回收,因为没有人将其设置为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.

huangapple
  • 本文由 发表于 2022年9月21日 20:45:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/73800980.html
匿名

发表评论

匿名网友

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

确定