go map搬迁的实现
本文主要介绍了go map搬迁的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
const (
    // Maximum number of key/elem pairs a bucket can hold.
    bucketCntBits = 3
    bucketCnt     = 1 << bucketCntBits

    // Maximum average load of a bucket that triggers growth is 6.5.
    // Represent as loadFactorNum/loadFactorDen, to allow integer math.
    loadFactorNum = 13
    loadFactorDen = 2
)

// 在元素数量大于8且元素数量大于负载因子(6.5)*桶总数,就要进行扩容
func overLoadFactor(count int, B uint8) bool {
    return count > bucketCnt && uintptr(count) > loadFactorNum*(bucketShift(B)/loadFactorDen)
}
// overflow buckets 太多
func tooManyOverflowBuckets(noverflow uint16, B uint8) bool {
    if B > 15 {
        B = 15
    }
    return noverflow >= uint16(1)<<(B&15)
}
func hashGrow(t *maptype, h *hmap) {
    // 判断是bucket多还是overflow多,然后根据这两种情况去申请新buckets空间
    bigger := uint8(1)
    if !overLoadFactor(h.count+1, h.B) {
        bigger = 0
        h.flags |= sameSizeGrow
    }
    oldbuckets := h.buckets
    newbuckets, nextOverflow := makeBucketArray(t, h.B+bigger, nil)

    flags := h.flags &^ (iterator | oldIterator)
    if h.flags&iterator != 0 {
        flags |= oldIterator
    }
    // commit the grow (atomic wrt gc)
  // 更新最新的bucket总数、将原桶标记为旧桶(后面判断是否在搬迁就是通过这个进行判断的)
    h.B += bigger
    h.flags = flags
    h.oldbuckets = oldbuckets
    h.buckets = newbuckets
  // 初始化搬迁进度为0
    h.nevacuate = 0
  // 初始化新桶overflow数量为0
    h.noverflow = 0

  // 将原来extra的overflow挂载到old overflow,代表这已经是旧的了
    if h.extra != nil && h.extra.overflow != nil {
        // Promote current overflow buckets to the old generation.
        if h.extra.oldoverflow != nil {
            throw("oldoverflow is not nil")
        }
        h.extra.oldoverflow = h.extra.overflow
        h.extra.overflow = nil
    }
  // extra指向下一块空闲的overflow空间
    if nextOverflow != nil {
        if h.extra == nil {
            h.extra = new(mapextra)
        }
        h.extra.nextOverflow = nextOverflow
    }
}
func growWork(t *maptype, h *hmap, bucket uintptr) {
    // make sure we evacuate the oldbucket corresponding
    // to the bucket we're about to use
    evacuate(t, h, bucket&h.oldbucketmask())

    // evacuate one more oldbucket to make progress on growing
    if h.growing() {
        evacuate(t, h, h.nevacuate)
    }
}
        // xy contains the x and y (low and high) evacuation destinations.
        var xy [2]evacDst
        x := &xy[0]
        x.b = (*bmap)(add(h.buckets, oldbucket*uintptr(t.bucketsize)))
        x.k = add(unsafe.Pointer(x.b), dataOffset)
        x.e = add(x.k, bucketCnt*uintptr(t.keysize))

        if !h.sameSizeGrow() {
            // Only calculate y pointers if we're growing bigger.
            // Otherwise GC can see bad pointers.
            y := &xy[1]
      // newBit在扩容的情况下等于1<<(B-1)
            y.b = (*bmap)(add(h.buckets, (oldbucket+newbit)*uintptr(t.bucketsize)))
            y.k = add(unsafe.Pointer(y.b), dataOffset)
            y.e = add(y.k, bucketCnt*uintptr(t.keysize))
        }
for ; b != nil; b = b.overflow(t) {
  // 找到key开始位置k,和value开始位置e
    k := add(unsafe.Pointer(b), dataOffset)
    e := add(k, bucketCnt*uintptr(t.keysize))
  // 遍历bucket中元素进行搬迁
    for i := 0; i < bucketCnt; i, k, e = i+1, add(k, uintptr(t.keysize)), add(e, uintptr(t.elemsize)) {
    // 获取tophash,若发现是空,说明已经搬迁过。并标记为空且已搬迁
        top := b.tophash[i]
        if isEmpty(top) {
            b.tophash[i] = evacuatedEmpty
            continue
        }
        if top < minTopHash {
            throw("bad map state")
        }
        k2 := k
    // 若key为引用类型就解引用
        if t.indirectkey() {
            k2 = *((*unsafe.Pointer)(k2))
        }
    // X指的就是原序号桶
    // Y指的就是扩容情况下,新的最高位为1的时候应该去的桶
        var useY uint8
        if !h.sameSizeGrow() {
            // Compute hash to make our evacuation decision (whether we need
            // to send this key/elem to bucket x or bucket y).
            hash := t.hasher(k2, uintptr(h.hash0))
      // 若正在迭代,且key为NaNs。是不是使用Y就取决最低位是不是1了
            if h.flags&iterator != 0 && !t.reflexivekey() && !t.key.equal(k2, k2) {
                useY = top & 1
                top = tophash(hash)
            } else {
        // 如果最高位为1,那么就应该选Y桶
                if hash&newbit != 0 {
                    useY = 1
                }
            }
        }

        if evacuatedX+1 != evacuatedY || evacuatedX^1 != evacuatedY {
            throw("bad evacuatedN")
        }

    // 标记X还是Y搬迁,并依此获取到搬迁目标桶
        b.tophash[i] = evacuatedX + useY 
        dst := &xy[useY]                 

    // 若目标桶已经超出桶容量,就分配新overflow
        if dst.i == bucketCnt {
            dst.b = h.newoverflow(t, dst.b)
            dst.i = 0
            dst.k = add(unsafe.Pointer(dst.b), dataOffset)
            dst.e = add(dst.k, bucketCnt*uintptr(t.keysize))
        }
    // 更新元素目标桶对应的tophash
    // 采用与而非取模,应该是出于性能目的
        dst.b.tophash[dst.i&(bucketCnt-1)] = top
    // 复制key到目标桶
        if t.indirectkey() {
            *(*unsafe.Pointer)(dst.k) = k2 // copy pointer
        } else {
            typedmemmove(t.key, dst.k, k) // copy elem
        }
    // 复制value到目标桶
        if t.indirectelem() {
            *(*unsafe.Pointer)(dst.e) = *(*unsafe.Pointer)(e)
        } else {
            typedmemmove(t.elem, dst.e, e)
        }
    
    // 更新目标桶元素数量、key、value位置
        dst.i++
        // These updates might push these pointers past the end of the key or elem arrays.   
    // That's ok, as we have the overflow pointer at the end of the bucket to protect against pointing past the end of the bucket.
        dst.k = add(dst.k, uintptr(t.keysize))
        dst.e = add(dst.e, uintptr(t.elemsize))
    }
}
        // Unlink the overflow buckets & clear key/elem to help GC.
        if h.flags&oldIterator == 0 && t.bucket.ptrdata != 0 {
      // 计算当前原bucket所在的开始位置b
            b := add(h.oldbuckets, oldbucket*uintptr(t.bucketsize))
            // Preserve b.tophash because the evacuation
            // state is maintained there.
      // 从开始位置加上key-value的偏移量,那么ptr所在的位置就是实际key-value的开始位置
            ptr := add(b, dataOffset)
      // n是总bucket大小减去key-value的偏移量,就key-value占用空间的大小
            n := uintptr(t.bucketsize) - dataOffset
      // 清理从ptr开始的n个字节
            memclrHasPointers(ptr, n)
        }
func advanceEvacuationMark(h *hmap, t *maptype, newbit uintptr) {
  // 更新进度
    h.nevacuate++
    // Experiments suggest that 1024 is overkill by at least an order of magnitude.
    // Put it in there as a safeguard anyway, to ensure O(1) behavior.
  // 向后看,更新已经完成的进度
    stop := h.nevacuate + 1024
    if stop > newbit {
        stop = newbit
    }
    for h.nevacuate != stop && bucketEvacuated(t, h, h.nevacuate) {
        h.nevacuate++
    }
  // 若是完成搬迁,就释放掉old buckets、重置搬迁状态、释放原bucket挂载到extra的overflow指针
    if h.nevacuate == newbit { // newbit == # of oldbuckets
        // Growing is all done. Free old main bucket array.
        h.oldbuckets = nil
        // Can discard old overflow buckets as well.
        // If they are still referenced by an iterator,
        // then the iterator holds a pointers to the slice.
        if h.extra != nil {
            h.extra.oldoverflow = nil
        }
        h.flags &^= sameSizeGrow
    }
}

最新评论