summaryrefslogtreecommitdiffhomepage
path: root/syncs/shardvalue_go.go
blob: 8531993319d1eae185e96676531539a857b45b74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

//go:build !tailscale_go

package syncs

import (
	"runtime"
	"sync"
	"sync/atomic"
)

type shardValuePool struct {
	atomic.Int64
	sync.Pool
}

// NewShardValue constructs a new ShardValue[T] with a shard per CPU.
func NewShardValue[T any]() *ShardValue[T] {
	sp := &ShardValue[T]{
		shards: make([]T, runtime.NumCPU()),
	}
	sp.pool.New = func() any {
		i := sp.pool.Add(1) - 1
		return &sp.shards[i%int64(len(sp.shards))]
	}
	return sp
}

// One yields a pointer to a single shard value with best-effort P-locality.
func (sp *ShardValue[T]) One(yield func(*T)) {
	v := sp.pool.Get().(*T)
	yield(v)
	sp.pool.Put(v)
}