Skip to content

Conversation

@yihuang
Copy link

@yihuang yihuang commented Feb 15, 2024

Context

I'm experimenting with the optimistic concurrency control pattern using the IsoCopy feature, it should be useful in read-heavy scenarios, this patch is some necessary changes to enable this pattern.

type BTree[T any] struct {
	atomic.Pointer[btree.BTreeG[T]]
}

func NewBTree[T any](less func(a, b T) bool) *BTree[T] {
	tree := btree.NewBTreeGOptions[T](less, btree.Options{
		NoLocks:  true,
		ReadOnly: true,
	})
	t := &BTree[T]{}
	t.Store(tree)
	return t
}

func (bt *BTree[T]) Get(item T) (result T, ok bool) {
	return bt.Load().Get(item)
}

func (bt *BTree[T]) Set(item T) (prev T, ok bool) {
	for {
		t := bt.Load()
		c := t.Copy()
		prev, ok = c.Set(item)
		c.Freeze()
		if bt.CompareAndSwap(t, c) {
			return
		}
	}
}

The performance difference of different concurrency control strategies differs a lot based on the workload, for my local testing scenario, the CAS is faster than Mutex in some cases, but slower in some other extreme cases, but both are much faster than RWMutex.

@yihuang
Copy link
Author

yihuang commented Jan 4, 2026

To elaborate on this, the read-only mode is to avoid the mutation on the origin tree's isoid in the IsoCopy method, that makes IsoCopy to be a read-only method in this mode.

defer tr.unlock(!tr.readOnly)
}
if !tr.readOnly {
tr.isoid = newIsoID()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The read-only mode is mainly to avoid the mutation on this field, so that we can have a fully read-only tree instance but supports IsoCopy method at the same time.

Copy link
Author

@yihuang yihuang Jan 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An alternative approach is to simply add a new method IsoCopyReadOnly without adding a new mode, and make it callers's responsibility to avoid modify the origin tree in place. That'll make the PR less intrusive. WDYT?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant