Why the garbage collector won't know how to find the pointers? I looked at mallocgc and decided if the GC needs to scan this object based on the noscan flag.
在 2019年1月25日星期五 UTC+8下午10:58:44,Ian Lance Taylor写道: > > On Thu, Jan 24, 2019 at 11:58 PM <mount...@gmail.com <javascript:>> > wrote: > > > > go 1.11.1 source code is below: > > > > Generally speaking, make chan just pay attention to the presence or > absence of buf. > > > > When I saw the source code of make chan, I can understand case 1: chan > buf is 0, but can't understand case 2 & default. > > > > Who knows this principle? > > > > Thanks! > > > > var c *hchan > > switch { > > case size == 0 || elem.size == 0: > > // Queue or element size is zero. > > c = (*hchan)(mallocgc(hchanSize, nil, true)) > > // Race detector uses this location for synchronization. > > c.buf = c.raceaddr() > > case elem.kind&kindNoPointers != 0: > > // Elements do not contain pointers. > > // Allocate hchan and buf in one call. > > c = (*hchan)(mallocgc(hchanSize+uintptr(size)*elem.size, nil, > true)) > > c.buf = add(unsafe.Pointer(c), hchanSize) > > default: > > // Elements contain pointers. > > c = new(hchan) > > c.buf = mallocgc(uintptr(size)*elem.size, elem, true) > > } > > > First, let me say: please don't post screen shots. They are much > harder to read than ordinary text. I don't understand why anybody > ever posts screenshots of code, and I would be grateful for an > explanation. Thanks. > > What is happening in that code is that if the channel has a non-zero > buffer size, we need to allocate space to hold the elements in the > buffer. If the elements in the buffer do not contain any pointers, we > can optimize by allocating the channel structure (hchan) and the > buffer in a single memory allocation. If the elements do contain > pointers, then that won't work, because the garbage collector won't > know how to find the pointers. So in that case we allocate the hchan > struct and the buffer separately. Note the second argument to > mallocgc, which is the type of the memory being allocated. When there > are no pointers, we pass nil, which tells the garbage collector that > the allocation contains no pointers. In the pointer case, we pass the > element type. > > Ian > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.