Repository navigation
Expand file tree
/
Copy pathring_buffer_api.go
More file actions
56 lines (48 loc) · 1.68 KB
/
Copy pathring_buffer_api.go
File metadata and controls
56 lines (48 loc) · 1.68 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package lfring
// RingBuffer defines the behavior of ring buffer
type RingBuffer[T any] interface {
Offer(T) (success bool)
Poll() (value T, success bool)
PollNBatched(n uint64) (values []T, count uint64)
PollNInto(dst []T, max uint64) int
SingleProducerOffer(valueSupplier func() (v T, finish bool))
SingleConsumerPoll(valueConsumer func(T))
SingleConsumerPollVec(ret []T) (validCnt uint64)
}
// BufferType contains different type names of ring buffer
type BufferType int
const (
// Classical ring buffer is a classical implementation of ring buffer
Classical BufferType = iota
// NodeBased is a type of ring buffer that implemented as node based,
// see https://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
NodeBased
)
// New build a RingBuffer with BufferType and capacity.
// Expand capacity as power-of-two, to make head/tail calculate faster and simpler
func New[T any](t BufferType, capacity uint64) RingBuffer[T] {
realCapacity := findPowerOfTwo(capacity)
switch t {
case NodeBased:
return newNodeBased[T](realCapacity)
case Classical:
return newClassical[T](realCapacity)
default:
panic("shouldn't goes here.")
}
}
// findPowerOfTwo return the input number as round up to it's power of two
// The algorithm only care about the MSB of (givenNum -1), through the below procedure,
// the MSB will be spread to all lower bit than MSB. At last do (givenNum + 1) we
// can get power of two form of givenNum.
func findPowerOfTwo(givenMum uint64) uint64 {
givenMum--
givenMum |= givenMum >> 1
givenMum |= givenMum >> 2
givenMum |= givenMum >> 4
givenMum |= givenMum >> 8
givenMum |= givenMum >> 16
givenMum |= givenMum >> 32
givenMum++
return givenMum
}