首页 > 解决方案 > 模块`github.com/google/btree`中的`copyOnWriteContext`是什么意思?

问题描述

最近看了google/btree的源码。但我对 struct 感到困惑copyOnWriteContext。它用于node函数mutableFor中,如下所示

func (n *node) mutableFor(cow *copyOnWriteContext) *node {
    if n.cow == cow {
        return n
    }
    fmt.Println("new node?")
    out := cow.newNode()
    if cap(out.items) >= len(n.items) {
        out.items = out.items[:len(n.items)]
    } else {
        out.items = make(items, len(n.items), cap(n.items))
    }
    copy(out.items, n.items)
    // Copy children
    if cap(out.children) >= len(n.children) {
        out.children = out.children[:len(n.children)]
    } else {
        out.children = make(children, len(n.children), cap(n.children))
    }
    copy(out.children, n.children)
    return out
}

我查看了这个模块中的所有代码,发现只有一个地方创建了copyOnWriteContext的实例。这是创建树的时间。

func New(degree int) *BTree {
    return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize))
}

那么对于 是什么意思mutableForcopyOnWriteContext因为整个代码中只有一个。n.cow总是等于cow参数。

标签: b-tree

解决方案


n.cow 可以为零。

// freeNode frees a node within a given COW context, if it's owned by that
// context.  It returns what happened to the node (see freeType const
// documentation).
func (c *copyOnWriteContext) freeNode(n *node) freeType {
    if n.cow == c {
        // clear to allow GC
        n.items.truncate(0)
        n.children.truncate(0)
        n.cow = nil
        if c.freelist.freeNode(n) {
            return ftStored
        } else {
            return ftFreelistFull
        }
    } else {
        return ftNotOwned
    }
}

推荐阅读